import React, { useState, useEffect, useRef } from 'react';
import { ArrowLeft, Send, Phone, Video, MoreVertical, Search } from 'lucide-react';
import { useConversations, useMessages, useTypingIndicator, useOnlineStatus } from '../hooks/useMessaging';
import { User, Message, Conversation } from '../types';
import { useNavigate, useLocation } from 'react-router-dom';

interface IndividualMessagingProps {
  recipientUser?: User;
  conversationId?: number;
}

const IndividualMessaging: React.FC<IndividualMessagingProps> = ({ 
  recipientUser: propRecipientUser, 
  conversationId: propConversationId 
}) => {
  const navigate = useNavigate();
  const location = useLocation();
  
  // Get recipient user from location state or props
  const recipientUser = location.state?.recipientUser || propRecipientUser;
  const conversationId = location.state?.conversationId || propConversationId;
  
  const { createConversation, getConversationById } = useConversations();
  const { 
    messages, 
    sendMessage, 
    markAsRead, 
    isLoading, 
    loadMessages 
  } = useMessages(conversationId);
  const { typingUsers, isAnyoneTyping } = useTypingIndicator(conversationId);
  const { getUserStatus } = useOnlineStatus();
  
  const [newMessage, setNewMessage] = useState('');
  const [currentConversation, setCurrentConversation] = useState<Conversation | null>(null);
  const [isLoadingConversation, setIsLoadingConversation] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Auto-scroll to bottom when new messages arrive
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // Initialize conversation
  useEffect(() => {
    const initializeConversation = async () => {
      if (!recipientUser) {
        navigate('/conversations');
        return;
      }

      setIsLoadingConversation(true);
      
      try {
        let conversation: Conversation | null = null;
        
        // If conversationId is provided, try to get existing conversation
        if (conversationId) {
          conversation = getConversationById(conversationId);
        }
        
        // If no existing conversation, create a new direct conversation
        if (!conversation) {
          conversation = await createConversation('direct', [recipientUser.id]);
        }
        
        setCurrentConversation(conversation);
        
        // Load messages for this conversation
        if (conversation) {
          await loadMessages(1, 50);
          // Mark messages as read
          await markAsRead();
        }
      } catch (error) {
        console.error('Failed to initialize conversation:', error);
        // Show user-friendly error message
        alert('Failed to initialize conversation. Please try again.');
      } finally {
        setIsLoadingConversation(false);
      }
    };

    initializeConversation();
  }, [recipientUser, conversationId, createConversation, getConversationById, loadMessages, markAsRead, navigate]);

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

    try {
      await sendMessage(newMessage);
      setNewMessage('');
    } catch (error) {
      console.error('Failed to send message:', error);
      alert('Failed to send message. Please try again.');
    }
  };

  const handleTyping = (e: React.ChangeEvent<HTMLInputElement>) => {
    setNewMessage(e.target.value);
    
    // Clear existing timeout
    if (typingTimeoutRef.current) {
      clearTimeout(typingTimeoutRef.current);
    }
    
    // Set timeout to stop typing indicator
    typingTimeoutRef.current = setTimeout(() => {
      // Stop typing indicator logic would go here
    }, 3000);
  };

  const formatMessageTime = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60);
    
    if (diffInHours < 24) {
      return date.toLocaleTimeString('en-US', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    } else {
      return date.toLocaleDateString('en-US', { 
        month: 'short', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  };

  const getMessageStatus = (message: Message) => {
    if (message.is_read) {
      return '✓✓'; // Double check for read
    }
    return '✓'; // Single check for sent
  };

  const getOnlineStatus = () => {
    if (!recipientUser) return 'offline';
    return getUserStatus(recipientUser.id);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'busy': return 'bg-red-500';
      case 'away': return 'bg-yellow-500';
      default: return 'bg-gray-400';
    }
  };

  if (!recipientUser) {
    return (
      <div className="h-screen flex items-center justify-center bg-gray-100">
        <div className="text-center">
          <h3 className="text-lg font-medium text-gray-900 mb-2">No recipient selected</h3>
          <p className="text-gray-500">Please select a contact to start messaging.</p>
          <button
            onClick={() => navigate('/conversations')}
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Go to Conversations
          </button>
        </div>
      </div>
    );
  }

  if (isLoadingConversation) {
    return (
      <div className="h-screen flex items-center justify-center bg-gray-100">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading conversation...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen flex flex-col bg-white">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-white">
        <div className="flex items-center space-x-3">
          <button
            onClick={() => navigate('/conversations')}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <ArrowLeft className="h-5 w-5 text-gray-600" />
          </button>
          
          <div className="flex items-center space-x-3">
            <div className="relative">
              <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold">
                {recipientUser.designation.split(' ').map(n => n[0]).join('').slice(0, 2)}
              </div>
              <div className={`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${getStatusColor(getOnlineStatus())}`}></div>
            </div>
            
            <div>
              <h2 className="font-semibold text-gray-900">{recipientUser.designation}</h2>
              <p className="text-sm text-gray-500">
                {getOnlineStatus() === 'online' ? 'Online' : 
                 getOnlineStatus() === 'busy' ? 'Busy' :
                 getOnlineStatus() === 'away' ? 'Away' : 'Offline'}
              </p>
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-2">
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <Search className="h-5 w-5 text-gray-600" />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <Phone className="h-5 w-5 text-gray-600" />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <Video className="h-5 w-5 text-gray-600" />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <MoreVertical className="h-5 w-5 text-gray-600" />
          </button>
        </div>
      </div>

      {/* Messages Area */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
        {isLoading ? (
          <div className="flex justify-center">
            <div className="text-gray-500">Loading messages...</div>
          </div>
        ) : messages.length === 0 ? (
          <div className="flex justify-center">
            <div className="text-center text-gray-500">
              <p>No messages yet</p>
              <p className="text-sm">Start a conversation with {recipientUser.designation}</p>
            </div>
          </div>
        ) : (
          messages.map((message) => (
            <div
              key={message.id}
              className={`flex ${message.sender_id === recipientUser.id ? 'justify-start' : 'justify-end'}`}
            >
              <div className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                message.sender_id === recipientUser.id
                  ? 'bg-white text-gray-900 shadow-sm'
                  : 'bg-blue-600 text-white'
              }`}>
                <div className="text-sm">{message.content}</div>
                <div className={`text-xs mt-1 flex items-center justify-between ${
                  message.sender_id === recipientUser.id ? 'text-gray-500' : 'text-blue-100'
                }`}>
                  <span>{formatMessageTime(message.created_at)}</span>
                  {message.sender_id !== recipientUser.id && (
                    <span className="ml-2">{getMessageStatus(message)}</span>
                  )}
                </div>
              </div>
            </div>
          ))
        )}
        
        {/* Typing Indicator */}
        {isAnyoneTyping && (
          <div className="flex justify-start">
            <div className="bg-white text-gray-900 px-4 py-2 rounded-lg shadow-sm">
              <div className="flex items-center space-x-1">
                <div className="flex space-x-1">
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                </div>
                <span className="text-xs text-gray-500 ml-2">
                  {recipientUser.designation} is typing...
                </span>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </div>

      {/* Message Input */}
      <div className="p-4 border-t border-gray-200 bg-white">
        <form onSubmit={handleSendMessage} className="flex items-center space-x-3">
          <input
            type="text"
            value={newMessage}
            onChange={handleTyping}
            placeholder={`Message ${recipientUser.designation}...`}
            className="flex-1 px-4 py-2 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            disabled={isLoading}
          />
          <button
            type="submit"
            disabled={!newMessage.trim() || isLoading}
            className="p-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <Send className="h-5 w-5" />
          </button>
        </form>
      </div>
    </div>
  );
};

export default IndividualMessaging;
