import React, { useState, useEffect, useRef } from 'react';
import { ArrowLeft, Users, MoreVertical } from 'lucide-react';
import { useScreenSize } from '../../utils/responsive';
import { useAuth } from '../../contexts/AuthContext';
import MessageList from './MessageList';
import MessageInput from './MessageInput';
import TypingIndicator from './TypingIndicator';

const ChatArea = ({ conversation, messages, onNewMessage, onConversationUpdate }) => {
  const { user } = useAuth();
  const { isMobile } = useScreenSize();
  const [showSidebar, setShowSidebar] = useState(!isMobile);
  const [typingUsers, setTypingUsers] = useState([]);

  const getConversationTitle = () => {
    if (conversation.type === 'direct') {
      const otherParticipant = conversation.participants.find(p => p.user._id !== user.id);
      return otherParticipant?.user.displayName || 'Unknown User';
    } else {
      return conversation.name;
    }
  };

  const getParticipantCount = () => {
    if (conversation.type === 'direct') {
      return '1 member';
    } else {
      return `${conversation.participants.length} members`;
    }
  };

  const handleNewMessage = (message) => {
    onNewMessage(message);
    onConversationUpdate(conversation._id, message);
  };

  const handleTypingStart = (data) => {
    if (data.userId !== user.id) {
      setTypingUsers(prev => [...prev.filter(id => id !== data.userId), data.userId]);
    }
  };

  const handleTypingStop = (data) => {
    setTypingUsers(prev => prev.filter(id => id !== data.userId));
  };

  return (
    <div className="flex flex-col h-full bg-white dark:bg-gray-800">
      {/* Chat Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center space-x-3">
          {isMobile && (
            <button
              onClick={() => setShowSidebar(true)}
              className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              <ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
            </button>
          )}
          
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center text-white font-medium text-sm">
              {conversation.type === 'direct' ? (
                getConversationTitle().charAt(0).toUpperCase()
              ) : (
                <Users className="w-5 h-5" />
              )}
            </div>
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                {getConversationTitle()}
              </h2>
              <div className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400">
                <span>{getParticipantCount()}</span>
                {typingUsers.length > 0 && (
                  <>
                    <span>•</span>
                    <TypingIndicator userIds={typingUsers} />
                  </>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-2">
          <button className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
            <MoreVertical className="w-5 h-5 text-gray-600 dark:text-gray-400" />
          </button>
        </div>
      </div>

      {/* Messages Area */}
      <div className="flex-1 overflow-hidden">
        <MessageList
          messages={messages}
          conversation={conversation}
          onTypingStart={handleTypingStart}
          onTypingStop={handleTypingStop}
        />
      </div>

      {/* Message Input */}
      <MessageInput
        conversation={conversation}
        onSendMessage={handleNewMessage}
        onTypingStart={handleTypingStart}
        onTypingStop={handleTypingStop}
      />

      {/* Mobile Sidebar Overlay */}
      {isMobile && showSidebar && (
        <div className="fixed inset-0 z-40 lg:hidden">
          <div className="absolute inset-0 bg-black bg-opacity-50" onClick={() => setShowSidebar(false)}></div>
        </div>
      )}
    </div>
  );
};

export default ChatArea;