import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
  fetchFriends,
  fetchFriendRequests,
  acceptFriendRequest,
  rejectFriendRequest,
  cancelFriendRequest,
  removeFriend,
  sendFriendRequest,
  searchUsers,
  toSmallImageUrl,
} from '../../api/client';
import { useAuth } from '../../auth/AuthContext';
import './Friends.css';

export default function FriendsList({ onSelectUser, onClose }) {
  const { t } = useTranslation();
  const { authenticated } = useAuth();
  const [activeTab, setActiveTab] = useState('friends');
  const [friends, setFriends] = useState([]);
  const [requests, setRequests] = useState([]);
  const [loading, setLoading] = useState(true);

  // Add friend state
  const [addUsername, setAddUsername] = useState('');
  const [addLoading, setAddLoading] = useState(false);
  const [addError, setAddError] = useState('');
  const [addSuccess, setAddSuccess] = useState('');

  // Autocomplete state
  const [suggestions, setSuggestions] = useState([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [suggestionsLoading, setSuggestionsLoading] = useState(false);
  const searchTimeoutRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    if (!authenticated) return;

    const loadData = async () => {
      setLoading(true);
      const [friendsRes, requestsRes] = await Promise.all([
        fetchFriends(),
        fetchFriendRequests(),
      ]);
      console.log('[Friends] requestsRes:', requestsRes);
      console.log('[Friends] requests:', requestsRes?.requests);
      setFriends(friendsRes?.friends || []);
      setRequests(requestsRes?.requests || []);
      setLoading(false);
    };

    loadData();
  }, [authenticated]);

  // Search for users with debounce
  const doSearchUsers = async (query) => {
    if (!query || query.length < 2) {
      setSuggestions([]);
      setShowSuggestions(false);
      return;
    }

    setSuggestionsLoading(true);
    try {
      const res = await searchUsers(query);
      const users = res?.users || [];
      setSuggestions(users);
      setShowSuggestions(users.length > 0);
    } catch {
      setSuggestions([]);
    }
    setSuggestionsLoading(false);
  };

  const handleInputChange = (e) => {
    const value = e.target.value;
    setAddUsername(value);

    // Debounce search
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
    searchTimeoutRef.current = setTimeout(() => {
      doSearchUsers(value);
    }, 300);
  };

  const handleSelectSuggestion = (username) => {
    setAddUsername(username);
    setSuggestions([]);
    setShowSuggestions(false);
    inputRef.current?.focus();
  };

  // Cleanup timeout on unmount
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  const handleAccept = async (username) => {
    const res = await acceptFriendRequest(username);
    if (res?.ok) {
      setRequests((prev) => prev.filter((r) => r.username !== username));
      // Reload friends list
      const friendsRes = await fetchFriends();
      setFriends(friendsRes?.friends || []);
    }
  };

  const handleReject = async (username) => {
    const res = await rejectFriendRequest(username);
    if (res?.ok) {
      setRequests((prev) => prev.filter((r) => r.username !== username));
    }
  };

  const handleCancel = async (username) => {
    console.log('[Friends] Canceling request to:', username);
    const res = await cancelFriendRequest(username);
    console.log('[Friends] Cancel response:', res);
    if (res?.ok) {
      setRequests((prev) => prev.filter((r) => r.username !== username));
    }
  };

  const handleRemove = async (username) => {
    if (!window.confirm(t('friends.removeConfirm', { username }))) return;
    const res = await removeFriend(username);
    if (res?.ok) {
      setFriends((prev) => prev.filter((f) => f.username !== username));
    }
  };

  const handleAddFriend = async (e) => {
    e.preventDefault();
    const uname = addUsername.trim();
    if (!uname) return;

    setAddLoading(true);
    setAddError('');
    setAddSuccess('');

    const res = await sendFriendRequest(uname);
    setAddLoading(false);

    if (res?.ok) {
      setAddSuccess(t('friends.requestSent', { username: uname }));
      setAddUsername('');
      setTimeout(() => setAddSuccess(''), 3000);
    } else {
      setAddError(res?.error || res?.text || t('friends.couldNotSend'));
      setTimeout(() => setAddError(''), 4000);
    }
  };

  if (!authenticated) {
    return (
      <div className="friends-panel">
        <div className="friends-header">
          <span>{t('friends.title')}</span>
          {onClose && <button className="friends-close" onClick={onClose}>×</button>}
        </div>
        <div className="friends-empty">{t('friends.signInToSee')}</div>
      </div>
    );
  }

  return (
    <div className="friends-panel">
      <div className="friends-header">
        <span>{t('friends.title')}</span>
        {onClose && <button className="friends-close" onClick={onClose}>×</button>}
      </div>

      <div className="friends-tabs">
        <button
          className={`friends-tab ${activeTab === 'friends' ? 'active' : ''}`}
          onClick={() => setActiveTab('friends')}
        >
          {t('friends.friendsTab')} ({friends.length})
        </button>
        <button
          className={`friends-tab ${activeTab === 'requests' ? 'active' : ''}`}
          onClick={() => setActiveTab('requests')}
        >
          {t('friends.requestsTab')} {requests.filter(r => r.direction === 'received').length > 0 && <span className="friends-badge">{requests.filter(r => r.direction === 'received').length}</span>}
        </button>
      </div>

      {/* Add Friend Form */}
      <div className="friends-add-wrap">
        <form className="friends-add-form" onSubmit={handleAddFriend}>
          <input
            ref={inputRef}
            type="text"
            className="friends-add-input"
            placeholder={t('friends.addPlaceholder')}
            value={addUsername}
            onChange={handleInputChange}
            onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
            onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
            disabled={addLoading}
            autoComplete="off"
          />
          <button
            type="submit"
            className="friends-add-btn"
            disabled={addLoading || !addUsername.trim()}
            title={t('friends.sendRequest')}
          >
            {addLoading ? '...' : <i className="fa-solid fa-user-plus" />}
          </button>
        </form>

        {/* Suggestions dropdown */}
        {showSuggestions && suggestions.length > 0 && (
          <div className="friends-suggestions">
            {suggestions.map((s) => (
              <div
                key={s.id}
                className="friends-suggestion-item"
                onMouseDown={() => handleSelectSuggestion(s.username)}
              >
                <div className="friend-avatar">
                  {s.avatar_url ? (
                    <img src={toSmallImageUrl(s.avatar_url)} alt={s.username} />
                  ) : (
                    s.username[0]?.toUpperCase() || '?'
                  )}
                </div>
                <span>{s.username}</span>
              </div>
            ))}
          </div>
        )}
        {suggestionsLoading && <div className="friends-suggestions-loading">{t('friends.searching')}</div>}
      </div>
      {addError && <div className="friends-add-error">{addError}</div>}
      {addSuccess && <div className="friends-add-success">{addSuccess}</div>}

      <div className="friends-content">
        {loading ? (
          <div className="friends-loading">{t('common.loading')}</div>
        ) : activeTab === 'friends' ? (
          friends.length === 0 ? (
            <div className="friends-empty">{t('friends.noFriends')}</div>
          ) : (
            <div className="friends-list">
              {friends.map((friend) => (
                <div key={friend.id} className="friend-item">
                  <div
                    className="friend-info"
                    onClick={() => onSelectUser && onSelectUser(friend.username)}
                  >
                    <div className="friend-avatar">
                      {friend.username[0].toUpperCase()}
                    </div>
                    <span className="friend-name">{friend.username}</span>
                  </div>
                  <button
                    className="friend-action friend-action-remove"
                    onClick={() => handleRemove(friend.username)}
                    title={t('friends.removeFriend')}
                  >
                    <i className="fa-solid fa-user-minus" />
                  </button>
                </div>
              ))}
            </div>
          )
        ) : requests.length === 0 ? (
          <div className="friends-empty">{t('friends.noPending')}</div>
        ) : (
          <div className="friends-list">
            {requests.map((request) => {
              console.log('[Friends] Rendering request:', request.username, 'direction:', request.direction);
              return (
              <div key={request.id} className={`friend-item ${request.direction === 'sent' ? 'friend-item-sent' : 'friend-item-received'}`}>
                <div
                  className="friend-info"
                  onClick={() => onSelectUser && onSelectUser(request.username)}
                >
                  <div className="friend-avatar">
                    {request.avatar_url ? (
                      <img src={toSmallImageUrl(request.avatar_url)} alt={request.username} />
                    ) : (
                      request.username[0]?.toUpperCase() || '?'
                    )}
                  </div>
                  <div className="friend-info-text">
                    <span className="friend-name">{request.username}</span>
                    <span className="friend-request-direction">
                      {request.direction === 'sent'
                        ? t('friends.requestSentLabel', 'Request sent')
                        : t('friends.requestReceivedLabel', 'Wants to be your friend')}
                    </span>
                  </div>
                </div>
                <div className="friend-actions">
                  {request.direction === 'received' ? (
                    <>
                      <button
                        className="friend-action friend-action-accept"
                        onClick={() => handleAccept(request.username)}
                        title={t('friends.accept')}
                      >
                        <i className="fa-solid fa-check" />
                      </button>
                      <button
                        className="friend-action friend-action-reject"
                        onClick={() => handleReject(request.username)}
                        title={t('friends.reject')}
                      >
                        <i className="fa-solid fa-times" />
                      </button>
                    </>
                  ) : (
                    <button
                      className="friend-action friend-action-cancel"
                      onClick={() => handleCancel(request.username)}
                      title={t('friends.cancelRequest', 'Cancel request')}
                    >
                      <i className="fa-solid fa-times" />
                    </button>
                  )}
                </div>
              </div>
            );
          })}
          </div>
        )}
      </div>
    </div>
  );
}
