import React, { useEffect, useState, useRef } from 'react';
import { X, Image as ImageIcon, Send, MapPin, Loader2, Search, Smile, Users } from 'lucide-react';
import { useNotification } from '@/hooks/useNotification';

interface LiveChatModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: any;
  defaultChatUserId?: string | null;
}

export const LiveChatModal: React.FC<LiveChatModalProps> = ({
  isOpen,
  onClose,
  user,
  defaultChatUserId,
}) => {
  const notify = useNotification();

  const [connections, setConnections] = useState<any[]>([]);
  const [activeChatUser, setActiveChatUser] = useState<any | null>(null);
  const [chatMessages, setChatMessages] = useState<any[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [isLoadingContacts, setIsLoadingContacts] = useState(false);
  const [isLoadingMessages, setIsLoadingMessages] = useState(false);
  const [isSending, setIsSending] = useState(false);
  
  // Attachments
  const [attachedImage, setAttachedImage] = useState<File | null>(null);
  const [attachedImageUrl, setAttachedImageUrl] = useState<string | null>(null);
  const [attachedLocation, setAttachedLocation] = useState<{ latitude: number; longitude: number } | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

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

  // Fetch connections
  const fetchConnections = async () => {
    setIsLoadingContacts(true);
    try {
      const res = await fetch('/api/v1/connections', { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        // Accepted connections only
        const activeConns = data.filter((c: any) => c.status === 'ACCEPTED');
        setConnections(activeConns);
      }
    } catch (e) {
      console.error('[LiveChatModal] Error fetching connections:', e);
    } finally {
      setIsLoadingContacts(false);
    }
  };

  // Fetch conversation messages
  const fetchMessages = async (targetUserId: string) => {
    setIsLoadingMessages(true);
    try {
      const res = await fetch(`/api/v1/messages/${targetUserId}`, { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        setChatMessages(data || []);
      }
    } catch (e) {
      console.error('[LiveChatModal] Error fetching messages:', e);
    } finally {
      setIsLoadingMessages(false);
    }
  };

  // Load contacts when modal opens
  useEffect(() => {
    if (isOpen && user) {
      fetchConnections();
    }
  }, [isOpen, user]);

  // Set active chat user dynamically if default is provided
  useEffect(() => {
    if (isOpen && defaultChatUserId && connections.length > 0) {
      const conn = connections.find(
        (c: any) => c.targetUser?.id === defaultChatUserId || c.requester?.id === defaultChatUserId
      );
      if (conn) {
        const target = conn.targetUser?.id === user?.id ? conn.requester : conn.targetUser;
        setActiveChatUser(target);
      }
    }
  }, [isOpen, defaultChatUserId, connections]);

  // Load chat messages when activeChatUser shifts
  useEffect(() => {
    if (activeChatUser) {
      fetchMessages(activeChatUser.id);
      (window as any).activeChatUserId = activeChatUser.id;
    }
    return () => {
      (window as any).activeChatUserId = undefined;
    };
  }, [activeChatUser]);

  // Handle incoming live messages from custom window event dispatched by App.tsx socket
  useEffect(() => {
    const handleMessageReceived = (e: Event) => {
      const msg = (e as CustomEvent).detail;
      if (activeChatUser && (msg.senderId === activeChatUser.id || msg.receiverId === activeChatUser.id)) {
        setChatMessages((prev) => [...prev, msg]);
      } else {
        // Reload contacts to update latest message snippets/badge alerts
        fetchConnections();
      }
    };

    window.addEventListener('app:messageReceived', handleMessageReceived);
    return () => {
      window.removeEventListener('app:messageReceived', handleMessageReceived);
    };
  }, [activeChatUser]);

  // Scroll to chat baseline
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chatMessages]);

  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setAttachedImage(file);
      setAttachedImageUrl(URL.createObjectURL(file));
      notify({
        title: 'Đã đính kèm ảnh',
        message: `${file.name} đã được chọn để gửi.`,
        type: 'info',
      });
    }
  };

  const handleAttachGps = () => {
    if (!navigator.geolocation) {
      notify({
        title: 'Không được hỗ trợ',
        message: 'Trình duyệt của bạn không hỗ trợ định vị.',
        type: 'error',
      });
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setAttachedLocation({
          latitude: pos.coords.latitude,
          longitude: pos.coords.longitude,
        });
        notify({
          title: 'Đã đính kèm định vị',
          message: `Vị trí (${pos.coords.latitude.toFixed(4)}, ${pos.coords.longitude.toFixed(4)}) đã được ghi nhận.`,
          type: 'success',
        });
      },
      () => {
        notify({
          title: 'Lỗi định vị',
          message: 'Không thể lấy vị trí hiện tại. Hãy kiểm tra quyền GPS.',
          type: 'error',
        });
      }
    );
  };

  const handleSendMessage = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!newMessage.trim() && !attachedImage && !attachedLocation) return;
    if (!activeChatUser) return;

    setIsSending(true);
    try {
      let uploadedUrl: string | null = null;
      if (attachedImage) {
        const formData = new FormData();
        formData.append('file', attachedImage);
        const uploadRes = await fetch('/api/v1/upload', {
          method: 'POST',
          headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` },
          body: formData,
        });
        if (uploadRes.ok) {
          const uploadData = await uploadRes.json();
          uploadedUrl = uploadData.url;
        } else {
          throw new Error('Upload ảnh thất bại.');
        }
      }

      const bodyData = {
        receiverId: activeChatUser.id,
        content: newMessage,
        mediaUrl: uploadedUrl,
        latitude: attachedLocation?.latitude || null,
        longitude: attachedLocation?.longitude || null,
      };

      const sendRes = await fetch('/api/v1/messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify(bodyData),
      });

      if (sendRes.ok) {
        const sentMsg = await sendRes.json();
        setChatMessages((prev) => [...prev, sentMsg]);
        setNewMessage('');
        setAttachedImage(null);
        setAttachedImageUrl(null);
        setAttachedLocation(null);
      } else {
        throw new Error('Gửi tin nhắn thất bại.');
      }
    } catch (err: any) {
      notify({
        title: 'Lỗi',
        message: err.message || 'Không thể gửi tin nhắn.',
        type: 'error',
      });
    } finally {
      setIsSending(false);
    }
  };

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

  // Filter connections by search query
  const filteredConnections = connections.filter((conn: any) => {
    const friend = conn.targetUser?.id === user?.id ? conn.requester : conn.targetUser;
    return friend?.name?.toLowerCase().includes(searchQuery.toLowerCase());
  });

  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-4xl 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" /> Trò chuyện trực tiếp
          </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>

        {/* Workspace panel */}
        <div className="flex-1 flex flex-col md:flex-row min-h-0">
          
          {/* Left Column - Contacts Sidebar */}
          <div className="w-full md:w-80 border-r border-slate-800/80 flex flex-col min-h-0 bg-slate-950/20 shrink-0">
            <div className="p-3 border-b border-slate-800/50">
              <div className="relative">
                <input 
                  type="text" 
                  placeholder="Tìm kiếm bạn bè..." 
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full bg-slate-950/80 border border-slate-850 rounded-xl py-2 pl-9 pr-4 text-white placeholder-slate-500 focus:outline-none focus:border-indigo-650"
                />
                <Search className="w-4 h-4 text-slate-500 absolute left-3 top-2.5" />
              </div>
            </div>

            <div className="flex-1 overflow-y-auto p-2 space-y-1.5">
              {isLoadingContacts ? (
                <div className="flex justify-center items-center py-10">
                  <Loader2 className="w-6 h-6 text-slate-500 animate-spin" />
                </div>
              ) : filteredConnections.length === 0 ? (
                <div className="text-center text-slate-500 py-10 italic">
                  Không tìm thấy bạn bè nào.
                </div>
              ) : (
                filteredConnections.map((conn: any) => {
                  const friend = conn.targetUser?.id === user?.id ? conn.requester : conn.targetUser;
                  const isActive = activeChatUser?.id === friend.id;
                  
                  return (
                    <button
                      key={conn.id}
                      onClick={() => setActiveChatUser(friend)}
                      className={`w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left cursor-pointer ${
                        isActive 
                          ? 'bg-indigo-650 text-white font-bold' 
                          : 'bg-slate-950/20 hover:bg-slate-850 text-slate-300'
                      }`}
                    >
                      <div className="relative shrink-0">
                        <div className="w-10 h-10 rounded-full bg-slate-800 border border-slate-700 flex items-center justify-center overflow-hidden font-bold">
                          {friend.avatar ? (
                            <img src={friend.avatar} alt="Avatar" className="w-full h-full object-cover" />
                          ) : (
                            <span>{friend.name.charAt(0).toUpperCase()}</span>
                          )}
                        </div>
                        <span className="absolute bottom-0 right-0 w-2.5 h-2.5 bg-green-500 rounded-full border-2 border-slate-900" />
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="text-xs truncate font-bold">{friend.name}</div>
                        <div className={`text-[10px] truncate mt-0.5 ${isActive ? 'text-slate-200' : 'text-slate-500'}`}>
                          {friend.email}
                        </div>
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          </div>

          {/* Right Column - Active Chat View */}
          <div className="flex-1 flex flex-col min-w-0 bg-slate-950/40">
            {activeChatUser ? (
              <>
                {/* Active contact bar */}
                <div className="px-4 py-3 bg-slate-900/60 border-b border-slate-800/60 flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-slate-800 overflow-hidden flex items-center justify-center font-bold">
                    {activeChatUser.avatar ? (
                      <img src={activeChatUser.avatar} alt="Avatar" className="w-full h-full object-cover" />
                    ) : (
                      <span>{activeChatUser.name.charAt(0).toUpperCase()}</span>
                    )}
                  </div>
                  <div className="min-w-0">
                    <div className="font-bold text-white text-xs">{activeChatUser.name}</div>
                    <div className="text-[10px] text-green-400 flex items-center gap-1 font-semibold">
                      <span className="w-1.5 h-1.5 rounded-full bg-green-500 inline-block animate-pulse" /> Đang hoạt động
                    </div>
                  </div>
                </div>

                {/* Messages stream */}
                <div className="flex-1 overflow-y-auto p-4 space-y-3.5">
                  {isLoadingMessages ? (
                    <div className="h-full flex items-center justify-center">
                      <Loader2 className="w-8 h-8 text-indigo-400 animate-spin" />
                    </div>
                  ) : chatMessages.length === 0 ? (
                    <div className="h-full flex flex-col items-center justify-center text-center text-slate-500 gap-1.5">
                      <Smile className="w-8 h-8 text-slate-600" />
                      <span>Hãy gửi tin nhắn để bắt đầu cuộc trò chuyện.</span>
                    </div>
                  ) : (
                    chatMessages.map((msg: any) => {
                      const isMe = msg.senderId === user.id;
                      const dateStr = msg.createdAt ? new Date(msg.createdAt).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' }) : '';
                      return (
                        <div 
                          key={msg.id} 
                          className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}
                        >
                          <div className={`max-w-[75%] flex flex-col gap-1`}>
                            <div 
                              className={`p-3 rounded-2xl break-words text-xs shadow-md ${
                                isMe 
                                  ? 'bg-indigo-650 text-white rounded-tr-none' 
                                  : 'bg-slate-800/90 text-slate-100 rounded-tl-none'
                              }`}
                            >
                              {/* Attached Image */}
                              {msg.mediaUrl && (
                                <div className="mb-2 rounded-xl overflow-hidden max-w-xs border border-black/10">
                                  <img 
                                    src={msg.mediaUrl} 
                                    alt="Chat attachment" 
                                    className="max-h-40 w-full object-cover cursor-pointer"
                                    onClick={() => window.open(msg.mediaUrl, '_blank')}
                                  />
                                </div>
                              )}

                              {/* Attached Location */}
                              {msg.latitude && msg.longitude && (
                                <a 
                                  href={`https://maps.google.com/?q=${msg.latitude},${msg.longitude}`}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="mb-2 flex items-center gap-2 p-2 bg-black/20 hover:bg-black/30 rounded-xl text-[10px] text-blue-300 font-bold border border-blue-500/20"
                                >
                                  <MapPin className="w-4 h-4 text-rose-500 shrink-0" />
                                  <span>Vị trí: {msg.latitude.toFixed(5)}, {msg.longitude.toFixed(5)}</span>
                                </a>
                              )}

                              {msg.content && <p className="leading-relaxed whitespace-pre-wrap">{msg.content}</p>}
                            </div>
                            <span className={`text-[9px] text-slate-500 ${isMe ? 'text-right' : 'text-left'}`}>
                              {dateStr}
                            </span>
                          </div>
                        </div>
                      );
                    })
                  )}
                  <div ref={messagesEndRef} />
                </div>

                {/* Bottom Input Area */}
                <form onSubmit={handleSendMessage} className="p-3 bg-slate-900 border-t border-slate-800/80 flex flex-col gap-2 shrink-0">
                  {/* Attachment Previews */}
                  {(attachedImageUrl || attachedLocation) && (
                    <div className="flex flex-wrap gap-2 p-2 bg-slate-950/60 rounded-xl border border-slate-850">
                      {attachedImageUrl && (
                        <div className="relative w-14 h-14 rounded-lg overflow-hidden border border-slate-750">
                          <img src={attachedImageUrl} alt="Preview" className="w-full h-full object-cover" />
                          <button
                            type="button"
                            onClick={() => { setAttachedImage(null); setAttachedImageUrl(null); }}
                            className="absolute top-0.5 right-0.5 p-0.5 bg-black/70 hover:bg-black text-white rounded-full"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </div>
                      )}

                      {attachedLocation && (
                        <div className="flex items-center gap-1.5 px-3 py-1 bg-rose-950/30 text-rose-300 border border-rose-800/30 rounded-xl text-[10px] font-bold">
                          <MapPin className="w-3.5 h-3.5 text-rose-500 shrink-0" />
                          <span>Vị trí GPS</span>
                          <button
                            type="button"
                            onClick={() => setAttachedLocation(null)}
                            className="p-0.5 bg-rose-900/50 hover:bg-rose-900 text-white rounded-full ml-1"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </div>
                      )}
                    </div>
                  )}

                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      className="p-2.5 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-xl transition-all cursor-pointer shrink-0"
                      title="Đính kèm ảnh"
                    >
                      <ImageIcon className="w-4 h-4" />
                    </button>
                    <input 
                      type="file" 
                      ref={fileInputRef} 
                      accept="image/*"
                      onChange={handleImageSelect}
                      className="hidden" 
                    />

                    <button
                      type="button"
                      onClick={handleAttachGps}
                      className="p-2.5 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-xl transition-all cursor-pointer shrink-0"
                      title="Gửi vị trí định vị"
                    >
                      <MapPin className="w-4 h-4 text-rose-500" />
                    </button>

                    <input 
                      type="text" 
                      placeholder="Nhập tin nhắn..." 
                      value={newMessage}
                      onChange={(e) => setNewMessage(e.target.value)}
                      className="flex-1 bg-slate-950 border border-slate-800 rounded-xl py-2.5 px-4 text-white focus:outline-none focus:border-indigo-650"
                    />

                    <button
                      type="submit"
                      disabled={isSending || (!newMessage.trim() && !attachedImage && !attachedLocation)}
                      className="p-2.5 bg-indigo-650 hover:bg-indigo-600 disabled:opacity-50 text-white rounded-xl transition-all cursor-pointer shrink-0"
                    >
                      {isSending ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Send className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                </form>
              </>
            ) : (
              <div className="h-full flex flex-col items-center justify-center text-center p-8 gap-3">
                <div className="w-16 h-16 bg-slate-900 border border-slate-800 rounded-full flex items-center justify-center">
                  <Smile className="w-8 h-8 text-slate-600 animate-bounce" />
                </div>
                <div>
                  <div className="font-bold text-white text-sm">Chưa chọn bạn hội thoại</div>
                  <p className="text-slate-500 mt-1 max-w-xs mx-auto">Chọn một người bạn ở danh sách bên trái để bắt đầu cuộc trò chuyện riêng tư của bạn.</p>
                </div>
              </div>
            )}
          </div>

        </div>

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