import React, { useEffect, useState } from 'react';
import { X, Search, Users, UserPlus, UserCheck, MessageSquare, Trash2, Check, UserX, Loader2 } from 'lucide-react';
import { useNotification } from '@/hooks/useNotification';
import { useConfirm } from '@/hooks/useConfirm';

interface FriendsManagerModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: any;
  onOpenChatWithUser?: (userId: string) => void;
}

export const FriendsManagerModal: React.FC<FriendsManagerModalProps> = ({
  isOpen,
  onClose,
  user,
  onOpenChatWithUser,
}) => {
  const notify = useNotification();
  const confirm = useConfirm();

  const [activeTab, setActiveTab] = useState<'friends' | 'pending' | 'search'>('friends');
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);

  // Connection Lists
  const [connections, setConnections] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  const getHeaders = () => ({
    'Authorization': `Bearer ${localStorage.getItem('token')}`,
  });

  // Fetch direct connections list
  const fetchConnections = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/v1/connections', { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        setConnections(data || []);
      }
    } catch (e) {
      console.error('[FriendsManagerModal] Error fetching connections:', e);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (isOpen && user) {
      fetchConnections();
    }
  }, [isOpen, user]);

  // Handle connection search lookup
  const handleSearchUsers = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchQuery.trim()) return;

    setIsSearching(true);
    try {
      const res = await fetch(`/api/v1/users?q=${encodeURIComponent(searchQuery)}`, { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        // Filter out current user from search results
        setSearchResults((data || []).filter((u: any) => u.id !== user?.id));
      }
    } catch (e) {
      console.error('[FriendsManagerModal] Search error:', e);
    } finally {
      setIsSearching(false);
    }
  };

  // Accept/Reject friend request
  const handleUpdateStatus = async (connId: string, status: 'ACCEPTED' | 'REJECTED') => {
    try {
      const res = await fetch(`/api/v1/connections/${connId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ status }),
      });
      if (res.ok) {
        notify({
          title: 'Thành công',
          message: status === 'ACCEPTED' ? 'Đã chấp nhận kết nối.' : 'Đã từ chối kết nối.',
          type: 'success',
        });
        fetchConnections();
      } else {
        throw new Error('Cập nhật kết nối thất bại.');
      }
    } catch (err: any) {
      notify({
        title: 'Lỗi',
        message: err.message,
        type: 'error',
      });
    }
  };

  // Disconnect / Unfriend / Cancel request
  const handleDisconnect = async (connId: string, name: string) => {
    const ok = await confirm({
      title: 'Hủy kết nối?',
      message: `Bạn có chắc chắn muốn hủy kết nối với ${name} không?`,
    });
    if (!ok) return;

    try {
      const res = await fetch(`/api/v1/connections/${connId}`, {
        method: 'DELETE',
        headers: getHeaders(),
      });
      if (res.ok) {
        notify({
          title: 'Thành công',
          message: 'Hủy kết nối thành công.',
          type: 'success',
        });
        fetchConnections();
      } else {
        throw new Error('Lỗi hủy kết nối.');
      }
    } catch (err: any) {
      notify({
        title: 'Lỗi',
        message: err.message,
        type: 'error',
      });
    }
  };

  // Send request connection
  const handleSendRequest = async (receiverId: string) => {
    try {
      const res = await fetch('/api/v1/connections', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({ receiverId }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Gửi lời mời thất bại.');

      notify({
        title: 'Thành công',
        message: 'Đã gửi lời mời kết nối thành công.',
        type: 'success',
      });
      fetchConnections();
      // Reset search lists to update button states
      setSearchResults(prev => prev.map(u => u.id === receiverId ? { ...u, pendingSent: true } : u));
    } catch (err: any) {
      notify({
        title: 'Lỗi',
        message: err.message,
        type: 'error',
      });
    }
  };

  if (!isOpen || !user) return null;

  // Filter lists
  const activeFriends = connections.filter((c: any) => c.status === 'ACCEPTED');
  
  // Received pending requests
  const pendingRequests = connections.filter((c: any) => c.status === 'PENDING' && c.targetUser?.id === user?.id);

  const getStatusText = (targetUserId: string) => {
    const existing = connections.find(
      c => c.targetUser?.id === targetUserId || c.requester?.id === targetUserId
    );
    if (!existing) return null;
    if (existing.status === 'ACCEPTED') return 'FRIEND';
    if (existing.status === 'PENDING') {
      return existing.requester?.id === user?.id ? 'SENT' : 'RECEIVED';
    }
    return null;
  };

  return (
    <div className="fixed inset-0 z-[1000000] bg-black/70 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4 pointer-events-auto">
      <div className="bg-slate-900 w-full sm:max-w-xl h-[92vh] sm:h-[80vh] rounded-t-3xl sm:rounded-2xl flex flex-col overflow-hidden text-slate-200 text-xs border border-slate-800/80 shadow-2xl animate-in slide-in-from-bottom sm:zoom-in-95 duration-300">
        
        {/* Header */}
        <div className="px-5 py-4 border-b border-slate-800/60 flex justify-between items-center shrink-0">
          <span className="font-bold text-sm text-white flex items-center gap-2">
            <Users className="w-5 h-5 text-indigo-400" /> Danh sách bạn bè
          </span>
          <button 
            onClick={onClose} 
            className="p-1.5 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-lg transition-colors cursor-pointer"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Tab Selection Header */}
        <div className="bg-slate-950/40 p-2.5 border-b border-slate-850 flex gap-2 shrink-0">
          {[
            { id: 'friends', label: `Bạn bè (${activeFriends.length})` },
            { id: 'pending', label: `Lời mời (${pendingRequests.length})` },
            { id: 'search', label: 'Tìm bạn mới' }
          ].map((tab) => {
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex-1 py-2 rounded-xl text-center font-bold transition-all cursor-pointer ${
                  isActive 
                    ? 'bg-indigo-650 text-white shadow-md' 
                    : 'bg-slate-900/40 hover:bg-slate-850 text-slate-400'
                }`}
              >
                {tab.label}
              </button>
            );
          })}
        </div>

        {/* Content body */}
        <div className="flex-1 overflow-y-auto p-5">
          {isLoading && activeTab !== 'search' ? (
            <div className="h-full flex items-center justify-center flex-col gap-2 py-20">
              <Loader2 className="w-8 h-8 text-indigo-400 animate-spin" />
              <span className="text-slate-400 font-medium">Đang tải dữ liệu...</span>
            </div>
          ) : activeTab === 'friends' ? (
            activeFriends.length === 0 ? (
              <div className="h-full flex flex-col items-center justify-center text-center py-20 px-6 gap-3">
                <div className="w-16 h-16 bg-slate-850 rounded-full flex items-center justify-center border border-slate-800">
                  <Users className="w-8 h-8 text-slate-500" />
                </div>
                <div>
                  <div className="font-bold text-white text-sm">Chưa có bạn bè kết nối</div>
                  <p className="text-slate-500 mt-1 max-w-xs mx-auto">Chọn mục "Tìm bạn mới" để tìm kiếm và gửi lời mời kết bạn.</p>
                </div>
              </div>
            ) : (
              <div className="space-y-2.5">
                {activeFriends.map((conn) => {
                  const friend = conn.targetUser?.id === user?.id ? conn.requester : conn.targetUser;
                  return (
                    <div 
                      key={conn.id} 
                      className="p-3 bg-slate-950/40 border border-slate-850 rounded-xl flex items-center justify-between gap-3"
                    >
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-full bg-slate-850 overflow-hidden flex items-center justify-center font-bold border border-slate-800 shrink-0">
                          {friend.avatar ? (
                            <img src={friend.avatar} alt="Avatar" className="w-full h-full object-cover" />
                          ) : (
                            <span>{friend.name.charAt(0).toUpperCase()}</span>
                          )}
                        </div>
                        <div className="min-w-0">
                          <h5 className="font-bold text-white truncate text-xs">{friend.name}</h5>
                          <p className="text-[10px] text-slate-400 truncate mt-0.5">{friend.email}</p>
                        </div>
                      </div>

                      <div className="flex items-center gap-1.5 shrink-0">
                        <button
                          onClick={() => {
                            if (onOpenChatWithUser) {
                              onClose();
                              onOpenChatWithUser(friend.id);
                            }
                          }}
                          className="p-2 bg-indigo-650/15 hover:bg-indigo-650 text-indigo-400 hover:text-white rounded-xl transition-all cursor-pointer"
                          title="Nhắn tin nhanh"
                        >
                          <MessageSquare className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDisconnect(conn.id, friend.name)}
                          className="p-2 bg-rose-650/15 hover:bg-rose-650 text-rose-400 hover:text-white rounded-xl transition-all cursor-pointer"
                          title="Hủy kết bạn"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )
          ) : activeTab === 'pending' ? (
            pendingRequests.length === 0 ? (
              <div className="h-full flex flex-col items-center justify-center text-center py-20 px-6 gap-3">
                <div className="w-16 h-16 bg-slate-850 rounded-full flex items-center justify-center border border-slate-800">
                  <UserPlus className="w-8 h-8 text-slate-500" />
                </div>
                <div>
                  <div className="font-bold text-white text-sm">Không có lời mời kết bạn</div>
                  <p className="text-slate-500 mt-1 max-w-xs mx-auto">Bạn không có lời mời kết bạn nào đang chờ duyệt.</p>
                </div>
              </div>
            ) : (
              <div className="space-y-2.5">
                {pendingRequests.map((conn) => {
                  const requester = conn.requester;
                  return (
                    <div 
                      key={conn.id} 
                      className="p-3 bg-slate-950/40 border border-slate-850 rounded-xl flex items-center justify-between gap-3"
                    >
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-full bg-slate-850 overflow-hidden flex items-center justify-center font-bold border border-slate-800 shrink-0">
                          {requester.avatar ? (
                            <img src={requester.avatar} alt="Avatar" className="w-full h-full object-cover" />
                          ) : (
                            <span>{requester.name.charAt(0).toUpperCase()}</span>
                          )}
                        </div>
                        <div className="min-w-0">
                          <h5 className="font-bold text-white truncate text-xs">{requester.name}</h5>
                          <p className="text-[10px] text-slate-400 truncate mt-0.5">{requester.email}</p>
                        </div>
                      </div>

                      <div className="flex items-center gap-1.5 shrink-0">
                        <button
                          onClick={() => handleUpdateStatus(conn.id, 'ACCEPTED')}
                          className="px-3.5 py-1.5 bg-emerald-650 hover:bg-emerald-600 font-bold text-white rounded-xl text-[10px] transition-all flex items-center gap-1 cursor-pointer"
                        >
                          <Check className="w-3.5 h-3.5" /> Chấp nhận
                        </button>
                        <button
                          onClick={() => handleDisconnect(conn.id, requester.name)}
                          className="p-2 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-xl transition-all cursor-pointer"
                          title="Từ chối lời mời"
                        >
                          <UserX className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )
          ) : (
            // Search Tab panel
            <div className="space-y-4">
              <form onSubmit={handleSearchUsers} className="flex gap-2">
                <div className="flex-1 relative">
                  <input 
                    type="text" 
                    placeholder="Tìm theo Tên hoặc Số điện thoại..." 
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl py-2.5 pl-9 pr-4 text-white focus:outline-none focus:border-indigo-650"
                  />
                  <Search className="w-4 h-4 text-slate-500 absolute left-3 top-3.5" />
                </div>
                <button
                  type="submit"
                  disabled={isSearching || !searchQuery.trim()}
                  className="px-4 py-2.5 bg-indigo-650 hover:bg-indigo-600 disabled:opacity-50 text-white font-bold rounded-xl transition-all flex items-center gap-1 cursor-pointer shrink-0"
                >
                  {isSearching ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : 'Tìm kiếm'}
                </button>
              </form>

              <div className="space-y-2.5">
                {isSearching ? (
                  <div className="flex justify-center items-center py-10">
                    <Loader2 className="w-6 h-6 text-slate-500 animate-spin" />
                  </div>
                ) : searchResults.length === 0 ? (
                  searchQuery.trim() && (
                    <div className="text-center text-slate-500 py-10 italic">
                      Không tìm thấy kết quả phù hợp.
                    </div>
                  )
                ) : (
                  searchResults.map((u) => {
                    const status = getStatusText(u.id);
                    return (
                      <div 
                        key={u.id} 
                        className="p-3 bg-slate-950/40 border border-slate-850 rounded-xl flex items-center justify-between gap-3"
                      >
                        <div className="flex items-center gap-3 min-w-0">
                          <div className="w-10 h-10 rounded-full bg-slate-850 overflow-hidden flex items-center justify-center font-bold border border-slate-800 shrink-0">
                            {u.avatar ? (
                              <img src={u.avatar} alt="Avatar" className="w-full h-full object-cover" />
                            ) : (
                              <span>{u.name.charAt(0).toUpperCase()}</span>
                            )}
                          </div>
                          <div className="min-w-0">
                            <h5 className="font-bold text-white truncate text-xs">{u.name}</h5>
                            <p className="text-[10px] text-slate-400 truncate mt-0.5">{u.email}</p>
                          </div>
                        </div>

                        <div className="shrink-0">
                          {status === 'FRIEND' ? (
                            <span className="text-[10px] text-indigo-400 font-bold flex items-center gap-1">
                              <UserCheck className="w-3.5 h-3.5" /> Đã kết nối
                            </span>
                          ) : status === 'SENT' || u.pendingSent ? (
                            <span className="text-[10px] text-slate-500 italic">
                              Đã gửi lời mời
                            </span>
                          ) : status === 'RECEIVED' ? (
                            <span className="text-[10px] text-amber-400 font-semibold">
                              Chờ bạn duyệt
                            </span>
                          ) : (
                            <button
                              onClick={() => handleSendRequest(u.id)}
                              className="px-3.5 py-1.5 bg-slate-800 hover:bg-slate-700 font-bold text-slate-200 rounded-xl text-[10px] transition-all flex items-center gap-1 cursor-pointer"
                            >
                              <UserPlus className="w-3.5 h-3.5" /> Kết nối
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          )}
        </div>

      </div>
    </div>
  );
};
