import React, { useState } from 'react';
import { Plus, Search } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useApp } from '../context/AppContext';
import ChatWindow from '../components/UI/ChatWindow';

const Conversations: React.FC = () => {
  const navigate = useNavigate();
  const { conversations, messages, users, selectedConversation, setSelectedConversation } = useApp();
  const [searchQuery, setSearchQuery] = useState('');

  const filteredConversations = conversations.filter(conv => {
    if (conv.type === 'direct') {
      const participant = users.find(u => conv.participants.includes(u.id) && u.id !== 1);
      return participant?.name.toLowerCase().includes(searchQuery.toLowerCase());
    } else {
      return conv.name?.toLowerCase().includes(searchQuery.toLowerCase());
    }
  });

  const getConversationName = (conversation: typeof conversations[0]) => {
    if (conversation.type === 'direct') {
      const participant = users.find(u => conversation.participants.includes(u.id) && u.id !== 1);
      return participant?.name || 'Unknown';
    }
    return conversation.name || 'Group Chat';
  };

  const getConversationMessages = (conversationId: number) => {
    return messages.filter(msg => {
      const conv = conversations.find(c => c.id === conversationId);
      if (conv?.type === 'direct') {
        return conv.participants.includes(msg.senderId) && conv.participants.includes(msg.receiverId || 0);
      } else {
        return msg.groupId === conversationId;
      }
    });
  };

  const getConversationParticipants = (conversation: typeof conversations[0]) => {
    return users.filter(user => conversation.participants.includes(user.id));
  };

  const handleConversationClick = (conversation: typeof conversations[0]) => {
    if (conversation.type === 'direct') {
      const participant = users.find(u => conversation.participants.includes(u.id) && u.id !== 1);
      if (participant) {
        navigate('/individual-messaging', {
          state: {
            recipientUser: participant,
            conversationId: conversation.id
          }
        });
      }
    } else {
      setSelectedConversation(conversation);
    }
  };

  return (
    <div className="h-screen flex bg-gray-100">
      {/* Conversations List */}
      <div className="w-1/3 bg-white border-r border-gray-200 flex flex-col">
        <div className="p-4 border-b border-gray-200">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-xl font-semibold text-gray-900">Messages</h1>
            <button className="p-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors">
              <Plus className="h-5 w-5" />
            </button>
          </div>
          
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search conversations..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto">
          {filteredConversations.map(conversation => {
            const lastMessage = conversation.lastMessage;
            const participants = getConversationParticipants(conversation);
            
            return (
              <div
                key={conversation.id}
                onClick={() => handleConversationClick(conversation)}
                className={`p-4 border-b border-gray-100 cursor-pointer hover:bg-gray-50 transition-colors ${
                  selectedConversation?.id === conversation.id ? 'bg-blue-50 border-blue-200' : ''
                }`}
              >
                <div className="flex items-center space-x-3">
                  <div className="w-12 h-12 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold">
                    {getConversationName(conversation).split(' ').map(n => n[0]).join('').slice(0, 2)}
                  </div>
                  
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <h3 className="font-medium text-gray-900 truncate">
                        {getConversationName(conversation)}
                      </h3>
                      {lastMessage && (
                        <span className="text-xs text-gray-500">
                          {new Date(lastMessage.timestamp).toLocaleTimeString('en-US', { 
                            hour: '2-digit', 
                            minute: '2-digit' 
                          })}
                        </span>
                      )}
                    </div>
                    
                    {lastMessage && (
                      <p className="text-sm text-gray-600 truncate">
                        {lastMessage.content}
                      </p>
                    )}
                    
                    {conversation.unreadCount > 0 && (
                      <div className="flex justify-between items-center mt-1">
                        <span className="text-xs text-gray-500">
                          {conversation.type === 'group' ? `${participants.length} members` : 'Direct'}
                        </span>
                        <span className="bg-blue-600 text-white text-xs rounded-full px-2 py-1 min-w-[20px] text-center">
                          {conversation.unreadCount}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Chat Window */}
      <div className="flex-1">
        {selectedConversation ? (
          <ChatWindow
            conversation={selectedConversation}
            messages={getConversationMessages(selectedConversation.id)}
            participants={getConversationParticipants(selectedConversation)}
          />
        ) : (
          <div className="flex items-center justify-center h-full bg-white">
            <div className="text-center">
              <div className="w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center mx-auto mb-4">
                <Plus className="h-8 w-8 text-gray-400" />
              </div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">Select a conversation</h3>
              <p className="text-gray-500">Choose a conversation from the list to start messaging.</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Conversations;