'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { supportChatService, getErrorMessage } from '@/services';
import type { SupportChat, SupportMessage } from '@/services';

function getUserDisplayName(chat: SupportChat): string {
  const profile = chat.user.userProfile || chat.user.agentProfile;
  if (profile && (profile.firstName || profile.lastName)) {
    return [profile.firstName, profile.lastName].filter(Boolean).join(' ');
  }
  return chat.user.email;
}

function formatTime(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  if (diffDays < 7) return `${diffDays}d ago`;
  return date.toLocaleDateString();
}

function formatMessageTime(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

export default function SupportChatPage() {
  const [chats, setChats] = useState<SupportChat[]>([]);
  const [selectedChat, setSelectedChat] = useState<SupportChat | null>(null);
  const [messages, setMessages] = useState<SupportMessage[]>([]);
  const [messageInput, setMessageInput] = useState('');
  const [filter, setFilter] = useState<'OPEN' | 'CLOSED'>('OPEN');
  const [loading, setLoading] = useState(true);
  const [messagesLoading, setMessagesLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);

  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, []);

  const fetchChats = useCallback(async () => {
    try {
      const data = await supportChatService.getAllChats(filter);
      setChats(data);
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  }, [filter]);

  const fetchMessages = useCallback(async (chatId: string) => {
    try {
      const data = await supportChatService.getMessages(chatId);
      setMessages(data.messages);
      setTimeout(scrollToBottom, 100);
    } catch (err) {
      setError(getErrorMessage(err));
    }
  }, [scrollToBottom]);

  // Fetch chats on mount and filter change
  useEffect(() => {
    setLoading(true);
    setSelectedChat(null);
    setMessages([]);
    fetchChats();
  }, [fetchChats]);

  // Polling for real-time updates
  useEffect(() => {
    if (pollIntervalRef.current) {
      clearInterval(pollIntervalRef.current);
    }

    pollIntervalRef.current = setInterval(() => {
      fetchChats();
      if (selectedChat) {
        fetchMessages(selectedChat.id);
      }
    }, 5000);

    return () => {
      if (pollIntervalRef.current) {
        clearInterval(pollIntervalRef.current);
      }
    };
  }, [fetchChats, fetchMessages, selectedChat]);

  const handleSelectChat = async (chat: SupportChat) => {
    setSelectedChat(chat);
    setMessagesLoading(true);
    setMessages([]);
    try {
      const data = await supportChatService.getMessages(chat.id);
      setMessages(data.messages);
      if (chat.adminUnreadCount > 0) {
        await supportChatService.markAsRead(chat.id);
        fetchChats();
      }
      setTimeout(scrollToBottom, 100);
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setMessagesLoading(false);
    }
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedChat || !messageInput.trim() || sending) return;

    setSending(true);
    try {
      await supportChatService.sendMessage(selectedChat.id, messageInput.trim());
      setMessageInput('');
      await fetchMessages(selectedChat.id);
      fetchChats();
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setSending(false);
    }
  };

  const handleCloseChat = async (chatId: string) => {
    try {
      await supportChatService.closeChat(chatId);
      if (selectedChat?.id === chatId) {
        setSelectedChat(null);
        setMessages([]);
      }
      fetchChats();
    } catch (err) {
      setError(getErrorMessage(err));
    }
  };

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Support Chat</h1>
        <p className="text-gray-600 mt-1">Manage user support conversations</p>
      </div>

      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-700 text-sm">{error}</p>
          <button
            onClick={() => setError('')}
            className="text-red-500 text-xs underline mt-1"
          >
            Dismiss
          </button>
        </div>
      )}

      {/* Filter Tabs */}
      <div className="mb-4 flex space-x-2">
        <button
          onClick={() => setFilter('OPEN')}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
            filter === 'OPEN'
              ? 'bg-blue-600 text-white'
              : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
          }`}
        >
          Open
        </button>
        <button
          onClick={() => setFilter('CLOSED')}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
            filter === 'CLOSED'
              ? 'bg-blue-600 text-white'
              : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
          }`}
        >
          Closed
        </button>
      </div>

      {/* Two-Panel Layout */}
      <div className="bg-white rounded-lg shadow flex" style={{ height: 'calc(100vh - 240px)' }}>
        {/* Left Panel - Chat List */}
        <div className="w-80 border-r border-gray-200 flex flex-col">
          <div className="px-4 py-3 border-b border-gray-200">
            <h2 className="text-sm font-semibold text-gray-700">
              Conversations ({chats.length})
            </h2>
          </div>
          <div className="flex-1 overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              </div>
            ) : chats.length === 0 ? (
              <div className="p-4 text-center text-gray-500 text-sm">
                No {filter.toLowerCase()} conversations
              </div>
            ) : (
              chats.map((chat) => (
                <button
                  key={chat.id}
                  onClick={() => handleSelectChat(chat)}
                  className={`w-full text-left px-4 py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors ${
                    selectedChat?.id === chat.id ? 'bg-blue-50' : ''
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-900 truncate">
                      {getUserDisplayName(chat)}
                    </span>
                    <div className="flex items-center space-x-2">
                      {chat.adminUnreadCount > 0 && (
                        <span className="inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-red-500 rounded-full">
                          {chat.adminUnreadCount}
                        </span>
                      )}
                      <span className={`px-2 py-0.5 text-xs font-semibold rounded-full ${
                        chat.status === 'OPEN'
                          ? 'bg-green-100 text-green-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}>
                        {chat.status}
                      </span>
                    </div>
                  </div>
                  {chat.lastMessageText && (
                    <p className="text-xs text-gray-500 mt-1 truncate">
                      {chat.lastMessageText}
                    </p>
                  )}
                  {chat.lastMessageAt && (
                    <p className="text-xs text-gray-400 mt-0.5">
                      {formatTime(chat.lastMessageAt)}
                    </p>
                  )}
                </button>
              ))
            )}
          </div>
        </div>

        {/* Right Panel - Messages */}
        <div className="flex-1 flex flex-col">
          {selectedChat ? (
            <>
              {/* Chat Header */}
              <div className="px-6 py-3 border-b border-gray-200 flex items-center justify-between">
                <div>
                  <h3 className="text-sm font-semibold text-gray-900">
                    {getUserDisplayName(selectedChat)}
                  </h3>
                  <p className="text-xs text-gray-500">{selectedChat.user.email}</p>
                </div>
                {selectedChat.status === 'OPEN' && (
                  <button
                    onClick={() => handleCloseChat(selectedChat.id)}
                    className="px-3 py-1.5 text-xs font-medium bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
                  >
                    Close Chat
                  </button>
                )}
              </div>

              {/* Messages Area */}
              <div className="flex-1 overflow-y-auto px-6 py-4 space-y-3">
                {messagesLoading ? (
                  <div className="flex items-center justify-center py-12">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                  </div>
                ) : messages.length === 0 ? (
                  <div className="text-center text-gray-500 text-sm py-12">
                    No messages yet
                  </div>
                ) : (
                  messages.map((message) => {
                    const isAdmin = message.senderRole === 'ADMIN';
                    return (
                      <div
                        key={message.id}
                        className={`flex ${isAdmin ? 'justify-end' : 'justify-start'}`}
                      >
                        <div
                          className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                            isAdmin
                              ? 'bg-blue-600 text-white'
                              : 'bg-gray-100 text-gray-900'
                          }`}
                        >
                          <p className="text-sm whitespace-pre-wrap">{message.content}</p>
                          <p
                            className={`text-xs mt-1 ${
                              isAdmin ? 'text-blue-200' : 'text-gray-400'
                            }`}
                          >
                            {formatMessageTime(message.createdAt)}
                          </p>
                        </div>
                      </div>
                    );
                  })
                )}
                <div ref={messagesEndRef} />
              </div>

              {/* Input Area */}
              {selectedChat.status === 'OPEN' && (
                <form
                  onSubmit={handleSendMessage}
                  className="px-6 py-3 border-t border-gray-200 flex items-center space-x-3"
                >
                  <input
                    type="text"
                    value={messageInput}
                    onChange={(e) => setMessageInput(e.target.value)}
                    placeholder="Type a message..."
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm text-gray-900 bg-white placeholder:text-gray-500"
                  />
                  <button
                    type="submit"
                    disabled={!messageInput.trim() || sending}
                    className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
                  >
                    {sending ? (
                      <svg className="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                    ) : (
                      'Send'
                    )}
                  </button>
                </form>
              )}

              {selectedChat.status === 'CLOSED' && (
                <div className="px-6 py-3 border-t border-gray-200 text-center">
                  <p className="text-sm text-gray-500">This conversation has been closed</p>
                </div>
              )}
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center">
              <div className="text-center">
                <svg
                  className="w-16 h-16 text-gray-300 mx-auto mb-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={1.5}
                    d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                  />
                </svg>
                <p className="text-gray-500 text-sm">Select a conversation to view messages</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
