import React, { useState, useRef, useEffect } from 'react';
import { sendChatMessage, getChatHistory } from '../api/agentsAPI';
import { Agent } from '../interfaces/AgentInterfaces';
import useCharacters from '../hooks/useCharacters';
import { User, Send } from 'lucide-react';
import { Message, ChatHistory } from '../interfaces/ChatInterfaces';
import Sidebar from '../components/sidebar';
import { motion, AnimatePresence } from 'framer-motion';
import { useAgent } from '../context/AgentContext';

const ChatToAgent: React.FC = () => {
  const { selectedAgent: contextAgent, setSelectedAgent: setContextAgent } = useAgent();
  const [selectedAgent, setSelectedAgent] = useState<Agent | null>(null);
  const { characters } = useCharacters();
  const [input, setInput] = useState('');
  const [chatHistory, setChatHistory] = useState<ChatHistory>({
    agent_name: '',
    chat_history: []
  });
  const [displayChatHistory, setDisplayChatHistory] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [selectedCharacterIndex, setSelectedCharacterIndex] = useState<number>(-1);

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

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

  useEffect(() => {
    if (contextAgent) {
      const index = characters.findIndex(
        (char) => char.agent.agent_details.name === contextAgent.agent.agent_details.name
      );
      setSelectedCharacterIndex(index);
      setSelectedAgent(contextAgent);
    }
  }, [contextAgent, characters]);

  useEffect(() => {
    const loadChatHistory = async () => {
      if (selectedAgent?.agent?.agent_details?.name) {
        try {
          const agentName = selectedAgent.agent.agent_details.name;
          const masterFilePath = selectedAgent.agent.master_file_path ||
            `configs/${agentName}/${agentName}_master.json`;
          const history = await getChatHistory(masterFilePath);
          setChatHistory(history);
          setDisplayChatHistory(history.chat_history || []);
        } catch (error) {
          console.error('Error loading chat history:', error);
          setChatHistory({
            agent_name: selectedAgent.agent.agent_details.name,
            chat_history: []
          });
          setDisplayChatHistory([]);
        }
      }
    };
    loadChatHistory();
  }, [selectedAgent]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || !selectedAgent) return;
  
    const userMessage: Message = {
      role: 'user',
      prompt: input.trim(),
      message_id: chatHistory.chat_history.length
    };
  
    // Immediately update the display with the user's message
    const updatedHistory = {
      ...chatHistory,
      chat_history: [...chatHistory.chat_history, userMessage]
    };
    setChatHistory(updatedHistory);
    setDisplayChatHistory(updatedHistory.chat_history);
    
    setInput('');
    setIsLoading(true);
  
    try {
      const agentName = selectedAgent?.agent?.agent_details?.name || '';
      const masterFilePath = selectedAgent?.agent?.master_file_path || 
        `configs/${agentName.replace(/\s+/g, '_')}/${agentName.replace(/\s+/g, '_')}_master.json`;
  
      const response = await sendChatMessage(
        masterFilePath,
        userMessage.prompt,
        chatHistory // Send original chatHistory
      );
  
      // Update with the complete response including both user message and agent response
      if (response.chat_history) {
        setChatHistory(response.chat_history);
        setDisplayChatHistory(response.chat_history.chat_history);
      }
    } catch (error) {
      console.error('Error sending message:', error);
      // Error state is already handled since we showed the user message
    } finally {
      setIsLoading(false);
    }
  };

  const handleAgentSelect = (index: number) => {
    const char = characters[index];
    if (char) {
      setSelectedCharacterIndex(index);
      setSelectedAgent(char);
      setContextAgent(char); // Update the context when selecting from dropdown
      setDisplayChatHistory([]);
    }
  };

  const getMessageContent = (message: Message) => {
    if (message.role === 'user') {
      return message.prompt || message.message;
    }
    return message.response;
  };

  return (
    <div className="flex min-h-screen bg-gray-50">
      <Sidebar />
      <div className="flex-1 flex flex-col">
        <div className="p-6 bg-white shadow-lg">
          <div className="max-w-7xl mx-auto flex items-center justify-between">
            <h1 className="text-3xl font-bold text-gray-600 font-orbitron">
              Interact with Agents
            </h1>
            <div className="flex items-center space-x-4">
            </div>
          </div>
        </div>

        <div className="p-6">
          <div className="max-w-7xl mx-auto">
            <motion.div 
              className="mb-6 flex justify-center"
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
            >
              <select
                className="px-4 py-2 rounded-lg bg-white border-2 border-yellow-400 text-gray-800 font-medium focus:outline-none focus:ring-2 focus:ring-yellow-400 transition-all duration-300"
                onChange={(e) => handleAgentSelect(parseInt(e.target.value))}
                value={selectedCharacterIndex}
              >
                <option value={-1}>Select an Agent</option>
                {characters.map((char, index) => (
                  <option key={index} value={index}>
                    {char.agent.agent_details.name}
                    {char.agent.master_file_path?.includes('_1') ? ' (1)' : ''}
                  </option>
                ))}
              </select>
            </motion.div>

            <div className="bg-white rounded-2xl shadow-xl h-[calc(100vh-300px)] flex flex-col">
              <div className="flex-1 overflow-y-auto p-6 space-y-6">
                <AnimatePresence>
                  {displayChatHistory.map((message) => (
                    <motion.div
                      key={message.message_id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -20 }}
                      className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
                    >
                      <div className="flex items-start space-x-4 max-w-[70%]">
                        {message.role !== 'user' && (
                          <div
                            className="w-10 h-10 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-600 flex-shrink-0"
                            style={{
                              backgroundImage: selectedAgent?.agent?.profile_image?.details?.url
                                ? `url(${selectedAgent?.agent?.profile_image?.details?.url})`
                                : undefined,
                              backgroundSize: 'cover',
                              backgroundPosition: 'center'
                            }}
                          />
                        )}

                        <div className={`flex flex-col ${message.role === 'user' ? 'items-end' : 'items-start'}`}>
                          <span className="text-sm text-gray-600 mb-1">
                            {message.role === 'user' ? 'You' : selectedAgent?.agent?.agent_details?.name}
                          </span>
                          <div
                            className={`p-4 rounded-2xl ${
                              message.role === 'user'
                                ? 'bg-yellow-400 text-gray-800'
                                : 'bg-gray-100 text-gray-800'
                            }`}
                          >
                            <p>{getMessageContent(message)}</p>
                          </div>
                        </div>

                        {message.role === 'user' && (
                          <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                            <User className="w-6 h-6 text-gray-600" />
                          </div>
                        )}
                      </div>
                    </motion.div>
                  ))}
                </AnimatePresence>

                {isLoading && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="flex justify-start"
                  >
                    <div className="flex items-center space-x-4">
                      <div className="w-10 h-10 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-600" />
                      <div className="bg-gray-100 p-4 rounded-2xl">
                        <div className="flex space-x-2">
                          <motion.div
                            animate={{ y: [-3, 0, -3] }}
                            transition={{ repeat: Infinity, duration: 1 }}
                            className="w-2 h-2 bg-yellow-400 rounded-full"
                          />
                          <motion.div
                            animate={{ y: [-3, 0, -3] }}
                            transition={{ repeat: Infinity, duration: 1, delay: 0.2 }}
                            className="w-2 h-2 bg-yellow-400 rounded-full"
                          />
                          <motion.div
                            animate={{ y: [-3, 0, -3] }}
                            transition={{ repeat: Infinity, duration: 1, delay: 0.4 }}
                            className="w-2 h-2 bg-yellow-400 rounded-full"
                          />
                        </div>
                      </div>
                    </div>
                  </motion.div>
                )}
                <div ref={messagesEndRef} />
              </div>

              <form onSubmit={handleSubmit} className="p-4 border-t border-gray-200">
                <div className="max-w-7xl mx-auto flex gap-4">
                  <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    placeholder={selectedAgent ? 'Type your message...' : 'Please select an agent first...'}
                    disabled={!selectedAgent || isLoading}
                    className="flex-1 px-4 py-2 rounded-lg bg-gray-100 border-2 border-transparent 
                            focus:border-yellow-400 focus:outline-none transition-all duration-300
                            text-gray-800 placeholder-gray-500"
                  />
                  <motion.button
                    type="submit"
                    disabled={!selectedAgent || isLoading}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    className="px-6 py-2 rounded-lg bg-yellow-400 text-gray-800 font-medium 
                            disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2
                            hover:bg-yellow-500 transition-colors duration-300"
                  >
                    <span>Send</span>
                    <Send className="w-4 h-4" />
                  </motion.button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ChatToAgent;