'use client';

import { useState, useEffect, useRef } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import { useWebSocketContext } from '@/context/WebSocketContext';
import './SimpleChat.css';

interface ChatMessage {
  id: string;
  content: string;
  senderId: string;
  senderName: string;
  senderAvatar: string;
  timestamp: string;
  isRead: boolean;
}

interface SimpleChatProps {
  projectId: string;
  bidId?: string;
  className?: string;
}

export default function SimpleChat({ projectId, bidId, className = '' }: SimpleChatProps) {
  const { data: session } = useSession();
  const { showError, showSuccess } = useToast();
  
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [messageInput, setMessageInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const [isTyping, setIsTyping] = useState(false);
  const [otherUserTyping, setOtherUserTyping] = useState(false);
  const [canSendMessage, setCanSendMessage] = useState(true);
  
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);

  const { isConnected, sendMessage: sendWebSocketMessage, joinRoom, leaveRoom, lastMessage } = useWebSocketContext();

  useEffect(() => {
    if (lastMessage) {
      handleWebSocketMessage(lastMessage);
    }
  }, [lastMessage]);

  // Initialize chat on mount
  useEffect(() => {
    if (projectId && session?.user?.email) {
      fetchMessages();
      
      // Join the appropriate room for this project/bid
      const roomId = bidId ? `bid_${bidId}` : `project_${projectId}`;
      if (isConnected) {
        joinRoom(roomId);
      }

      // Use polling as fallback if WebSocket is not connected
      if (!isConnected) {
        startPolling();
      }
    }

    return () => {
      if (isConnected) {
        const roomId = bidId ? `bid_${bidId}` : `project_${projectId}`;
        leaveRoom(roomId);
      }
      stopPolling();
    };
  }, [projectId, bidId, session?.user?.email, isConnected, joinRoom, leaveRoom]);

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleWebSocketMessage = (data: any) => {
    try {
      // Handle different message formats
      const message = typeof data === 'string' ? JSON.parse(data) : data;
      
      switch (message.type) {
        case 'new_message':
          if (message.message && message.message.id) {
            // Check if message is relevant to this project/bid
            const isRelevant = message.message.projectId === projectId;
            if (isRelevant) {
              setMessages(prev => {
                const exists = prev.find(msg => msg.id === message.message.id);
                if (!exists) {
                  return [...prev, {
                    id: message.message.id,
                    content: message.message.content,
                    senderId: message.message.senderId,
                    senderName: message.message.senderName || 'Unknown',
                    senderAvatar: message.message.senderAvatar || '/assets/image/default-avatar.png',
                    timestamp: message.message.timestamp || new Date().toISOString(),
                    isRead: message.message.isRead || false
                  }];
                }
                return prev;
              });
            }
          }
          break;
        case 'typing_start':
          if (message.userId !== session?.user?.email) {
            setOtherUserTyping(true);
          }
          break;
        case 'typing_stop':
          if (message.userId !== session?.user?.email) {
            setOtherUserTyping(false);
          }
          break;
        case 'message_read':
          if (message.messageIds && Array.isArray(message.messageIds)) {
            setMessages(prev => prev.map(msg => 
              message.messageIds.includes(msg.id) ? { ...msg, isRead: true } : msg
            ));
          }
          break;
        case 'error':
          console.warn('WebSocket error:', message.error);
          break;
        default:
          console.log('Unknown WebSocket message type:', message.type);
      }
    } catch (error) {
      console.error('Error processing WebSocket message:', error);
    }
  };

  const startPolling = () => {
    stopPolling();
    pollIntervalRef.current = setInterval(() => {
      if (projectId && !document.hidden) {
        fetchMessages();
      }
    }, 3000);
  };

  const stopPolling = () => {
    if (pollIntervalRef.current) {
      clearInterval(pollIntervalRef.current);
      pollIntervalRef.current = null;
    }
  };

  const fetchMessages = async () => {
    try {
      setIsLoading(true);
      const url = bidId 
        ? `/api/projects/${projectId}/chat/messages?bidId=${bidId}`
        : `/api/projects/${projectId}/chat/messages`;
      
      const response = await fetch(url);
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          if (result.data.messages) {
            setMessages(result.data.messages);
            setCanSendMessage(result.data.canSendMessage);
          } else {
            setMessages(result.data);
          }
        }
      }
    } catch (error) {
      console.error('Failed to load messages:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const sendMessage = async (content: string) => {
    if (!content.trim() || !canSendMessage) return;

    setIsSending(true);
    
    try {
      const url = bidId 
        ? `/api/projects/${projectId}/chat/send?bidId=${bidId}`
        : `/api/projects/${projectId}/chat/send`;
      
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          projectId,
          content: content.trim(),
          messageType: 'text'
        }),
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          // Message will be added via WebSocket if connected
          if (!isConnected) {
            setMessages(prev => [...prev, result.data]);
          }
        }
        setMessageInput('');
      } else {
        const errorData = await response.json();
        showError(errorData.error || 'Failed to send message');
      }
    } catch (error) {
      showError('Failed to send message. Please try again.');
    } finally {
      setIsSending(false);
    }
  };

  const handleSendMessage = (e: React.FormEvent) => {
    e.preventDefault();
    sendMessage(messageInput);
  };

  const handleTyping = (isTypingNow: boolean) => {
    if (isConnected) {
      const roomId = bidId ? `bid_${bidId}` : `project_${projectId}`;
      sendWebSocketMessage({
        type: isTypingNow ? 'typing_start' : 'typing_stop',
        roomId
      });
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setMessageInput(e.target.value);
    
    if (!isTyping && e.target.value.trim()) {
      setIsTyping(true);
      handleTyping(true);
    }

    if (typingTimeoutRef.current) {
      clearTimeout(typingTimeoutRef.current);
    }

    typingTimeoutRef.current = setTimeout(() => {
      setIsTyping(false);
      handleTyping(false);
    }, 1000);
  };

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

  const formatTime = (timestamp: string) => {
    return new Date(timestamp).toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: true
    });
  };

  return (
    <div className={`simple-chat ${className}`}>
      {/* Header */}
      <div className="chat-header">
        <div className="chat-title">
          <h4>Project Chat</h4>
          {isConnected && (
            <span className="status-indicator connected">
              Real-time
            </span>
          )}
        </div>
      </div>

      {/* Messages */}
      <div className="chat-messages">
        {isLoading ? (
          <div className="loading-state">
            <div className="spinner"></div>
            <p>Loading messages...</p>
          </div>
        ) : (
          <div className="messages-list">
            {messages.length === 0 ? (
              <div className="empty-state">
                <p>No messages yet. Start the conversation!</p>
              </div>
            ) : (
              messages.map((message) => (
                <div 
                  key={message.id}
                  className={`message ${
                    message.senderId === session?.user?.email ? 'sent' : 'received'
                  }`}
                >
                  <div className="message-avatar">
                    <img 
                      src={message.senderAvatar || '/assets/image/default-avatar.png'} 
                      alt={message.senderName}
                    />
                  </div>
                  <div className="message-content">
                    <div className="message-header">
                      <span className="sender-name">{message.senderName}</span>
                      <span className="message-time">{formatTime(message.timestamp)}</span>
                    </div>
                    <div className="message-body">
                      <p>{message.content}</p>
                    </div>
                    {message.senderId === session?.user?.email && (
                      <div className="message-status">
                        <span className={message.isRead ? 'read' : 'sent'}>
                          {message.isRead ? '✓✓' : '✓'}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              ))
            )}
            
            {/* Typing Indicator */}
            {otherUserTyping && (
              <div className="typing-indicator">
                <div className="typing-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <small>Typing...</small>
              </div>
            )}
            
            <div ref={messagesEndRef} />
          </div>
        )}
      </div>

      {/* Input */}
      <div className="chat-input">
        {!canSendMessage ? (
          <div className="chat-disabled">
            <p>Chat is disabled for this project.</p>
          </div>
        ) : (
          <form onSubmit={handleSendMessage} className="input-form">
            <input
              type="text"
              placeholder="Type your message..."
              value={messageInput}
              onChange={handleInputChange}
              disabled={isSending || !canSendMessage}
              className="message-input"
            />
            <button
              type="submit"
              disabled={isSending || !messageInput.trim() || !canSendMessage}
              className="send-button"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M2 21L23 12L2 3V10L17 12L2 14V21Z" fill="currentColor"/>
              </svg>
            </button>
          </form>
        )}
      </div>
    </div>
  );
}