import { useState, useEffect, useRef } from 'react';
import { Send } from 'lucide-react';
import { useLocation } from 'react-router-dom';
import { Avatar } from '../components/ui/Avatar';
import { api } from '../api/client';
import { useAuth } from '../context/AuthContext';
import { formatDate, formatCurrency } from '../utils/format';
import type { Conversation, Message } from '../types';

export function ChatPage() {
  const { user } = useAuth();
  const location = useLocation();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedConv, setSelectedConv] = useState<string | undefined>();
  const [messages, setMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    api.get<Conversation[]>('/chat/conversations')
      .then(convs => {
        setConversations(convs);
        const stateConvId = (location.state as { conversationId?: string })?.conversationId;
        if (stateConvId && convs.find(c => c.id === stateConvId)) {
          setSelectedConv(stateConvId);
        } else if (convs.length > 0 && !selectedConv) {
          setSelectedConv(convs[0].id);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (!selectedConv) return;
    api.get<{ data: Message[] }>(`/chat/conversations/${selectedConv}/messages`)
      .then(res => {
        setMessages(res.data);
        setTimeout(() => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
      })
      .catch(() => setMessages([]));
  }, [selectedConv]);

  const activeConv = conversations.find(c => c.id === selectedConv);
  const otherUser = activeConv
    ? (activeConv.user1.id === user?.id ? activeConv.user2 : activeConv.user1)
    : null;

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMessage.trim() || !selectedConv || !activeConv || sending) return;
    setSending(true);
    const recipientId = activeConv.user1.id === user?.id ? activeConv.user2.id : activeConv.user1.id;
    try {
      await api.post('/chat/conversations', {
        recipientId,
        listingId: activeConv.listing?.id,
        message: newMessage,
      });
      setNewMessage('');
      const res = await api.get<{ data: Message[] }>(`/chat/conversations/${selectedConv}/messages`);
      setMessages(res.data);
      setTimeout(() => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
    } catch {}
    setSending(false);
  };

  if (loading) return <div className="text-center text-gray-500 py-12">Loading conversations...</div>;

  return (
    <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden" style={{ height: 'calc(100vh - 200px)' }}>
      <div className="flex h-full">
        {/* Conversation List */}
        <div className="w-72 border-r border-gray-100 flex flex-col">
          <div className="p-4 border-b border-gray-100">
            <h2 className="font-bold text-gray-900">Messages</h2>
          </div>
          <div className="flex-1 overflow-y-auto">
            {conversations.length === 0 ? (
              <p className="p-4 text-sm text-gray-400">No conversations yet</p>
            ) : conversations.map(conv => {
              const other = conv.user1.id === user?.id ? conv.user2 : conv.user1;
              return (
                <button key={conv.id} onClick={() => setSelectedConv(conv.id)}
                  className={`w-full flex items-center gap-3 px-4 py-3 hover:bg-gray-50 transition-colors cursor-pointer
                    ${selectedConv === conv.id ? 'bg-primary-50' : ''}`}>
                  <Avatar name={other.fullName} size="md" />
                  <div className="flex-1 min-w-0 text-left">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-semibold text-gray-900 truncate">{other.nickname || other.fullName}</span>
                      <span className="text-xs text-gray-400 flex-shrink-0">{conv.lastMessage ? formatDate(conv.lastMessage.createdAt) : ''}</span>
                    </div>
                    <p className="text-xs text-gray-500 truncate">{conv.lastMessage?.content}</p>
                  </div>
                  {conv.unreadCount > 0 && (
                    <span className="w-5 h-5 bg-pink-500 text-white text-xs rounded-full flex items-center justify-center flex-shrink-0">{conv.unreadCount}</span>
                  )}
                </button>
              );
            })}
          </div>
        </div>

        {/* Chat Area */}
        <div className="flex-1 flex flex-col">
          {activeConv ? (
            <>
              <div className="p-4 border-b border-gray-100 flex items-center gap-3">
                <Avatar name={otherUser?.fullName || ''} size="sm" />
                <div>
                  <h3 className="text-sm font-semibold text-gray-900">{otherUser?.nickname || otherUser?.fullName}</h3>
                  {activeConv.listing && (
                    <p className="text-xs text-gray-500">{activeConv.listing.title} &middot; {formatCurrency(activeConv.listing.price)}</p>
                  )}
                </div>
              </div>

              <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {messages.map(msg => {
                  const isMe = msg.senderId === user?.id;
                  return (
                    <div key={msg.id} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                      <div className={`max-w-xs px-4 py-2.5 rounded-2xl text-sm
                        ${isMe ? 'bg-gradient-to-r from-primary-500 to-primary-600 text-white rounded-br-md' : 'bg-gray-100 text-gray-900 rounded-bl-md'}`}>
                        <p>{msg.content}</p>
                        <p className={`text-xs mt-1 ${isMe ? 'text-primary-200' : 'text-gray-400'}`}>{formatDate(msg.createdAt)}</p>
                      </div>
                    </div>
                  );
                })}
                <div ref={messagesEndRef} />
              </div>

              <form onSubmit={handleSend} className="p-4 border-t border-gray-100 flex gap-3">
                <input type="text" value={newMessage} onChange={(e) => setNewMessage(e.target.value)}
                  placeholder="Type a message..."
                  className="flex-1 px-4 py-2.5 rounded-xl border border-gray-200 bg-gray-50 text-sm focus:border-primary-400 focus:outline-none" />
                <button type="submit" disabled={sending}
                  className="p-2.5 rounded-xl bg-gradient-to-r from-pink-500 to-primary-600 text-white hover:from-pink-600 hover:to-primary-700 transition-all cursor-pointer disabled:opacity-50">
                  <Send className="w-5 h-5" />
                </button>
              </form>
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center text-gray-400">
              Select a conversation to start chatting
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
