"use client";

import { useState, useEffect, useRef } from 'react';
import { Job, Message } from '../types';

interface ChatScreenProps {
  job: Job;
  candidateName: string;
  linkId: string;
  isTestMode?: boolean;
  mandatoryAnswers?: string[];
  onComplete: () => void;
}

export default function ChatScreen({ job, candidateName, linkId, isTestMode = false, mandatoryAnswers = [], onComplete }: ChatScreenProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isInitializing, setIsInitializing] = useState(true);
  const [error, setError] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [typingMessage, setTypingMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

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

  // Build conversation history from mandatory answers for test mode
  const buildConversationHistory = () => {
    if (!isTestMode || !mandatoryAnswers.length) return [];
    
    const history: Message[] = [];
    const mandatoryQuestions = job.interview_questions || [];
    
    for (let i = 0; i < mandatoryQuestions.length; i++) {
      if (mandatoryAnswers[i]) {
        history.push({
          id: `q-${i + 1}`,
          sender: 'ai',
          content: `Question ${i + 1}: ${mandatoryQuestions[i]}`,
          timestamp: new Date()
        });
        history.push({
          id: `a-${i + 1}`,
          sender: 'user',
          content: mandatoryAnswers[i],
          timestamp: new Date()
        });
      }
    }
    
    return history;
  };

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

  // Typing effect function
  const simulateTyping = (text: string, onComplete: (finalText: string) => void) => {
    setIsTyping(true);
    setTypingMessage('');
    
    let currentIndex = 0;
    const typingSpeed = 20 + Math.random() * 30; // Random speed between 20-50ms per character
    
    const typeNextCharacter = () => {
      if (currentIndex < text.length) {
        setTypingMessage(text.slice(0, currentIndex + 1));
        currentIndex++;
        setTimeout(typeNextCharacter, typingSpeed);
      } else {
        setIsTyping(false);
        onComplete(text);
      }
    };
    
    // Small delay before starting to type
    setTimeout(typeNextCharacter, 500);
  };

  useEffect(() => {
    initializeChat();
  }, []);

  const initializeChat = async () => {
    try {
      setIsInitializing(true);
      
      // Send initial data to AI endpoint
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/rest/ai/start-interview${isTestMode ? '?test=true' : ''}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          candidateName,
          job: job,
          linkId,
          test: isTestMode
        })
      });

      if (response.ok) {
        const data = await response.json();
        
        // Use typing effect for AI's initial message
        const aiMessage = data.message || "Hello! I'm your evaluation agent. Let's begin the interview for the " + job.title + " position. Please tell me about yourself and your interest in this role.";
        
        simulateTyping(aiMessage, (finalText) => {
          setMessages([{
            id: '1',
            content: finalText,
            sender: 'ai',
            timestamp: new Date()
          }]);
        });
      } else {
        throw new Error('Failed to initialize chat');
      }
    } catch (error) {
      console.error('Error initializing chat:', error);
      setError('Failed to start the interview. Please try again.');
      
      // Add fallback message with typing effect
      const fallbackMessage = "Hello! I'm your evaluation agent. Let's begin the interview for the " + job.title + " position. Please tell me about yourself and your interest in this role.";
      
      simulateTyping(fallbackMessage, (finalText) => {
        setMessages([{
          id: '1',
          content: finalText,
          sender: 'ai',
          timestamp: new Date()
        }]);
      });
    } finally {
      setIsInitializing(false);
    }
  };

  const sendMessage = async () => {
    if (!inputMessage.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputMessage.trim(),
      sender: 'user',
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputMessage('');
    setIsLoading(true);

    try {
      // Build conversation history for test mode
      const conversationHistory = isTestMode ? 
        [...buildConversationHistory(), ...messages.filter(msg => msg.content && msg.content !== 'undefined')] : 
        messages;

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/rest/ai/chat${isTestMode ? '?test=true' : ''}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message: userMessage.content,
          candidateName,
          job: job,
          linkId,
          conversationHistory: conversationHistory.map(msg => ({
            sender: msg.sender === 'user' ? 'candidate' : msg.sender,
            message: msg.content,
            timestamp: msg.timestamp
          })),
          test: isTestMode
        })
      });

      if (response.ok) {
        const data = await response.json();
        
        // Use typing effect for AI response
        const aiResponseText = data.message || "Thank you for your response. Let me ask you another question...";
        
        simulateTyping(aiResponseText, (finalText) => {
          const aiMessage: Message = {
            id: (Date.now() + 1).toString(),
            content: finalText,
            sender: 'ai',
            timestamp: new Date()
          };

          setMessages(prev => [...prev, aiMessage]);

          // Check if interview is complete
          if (data.isComplete) {
            setTimeout(() => {
              onComplete();
            }, 2000);
          }
        });
      } else {
        throw new Error('Failed to send message');
      }
    } catch (error) {
      console.error('Error sending message:', error);
      setError('Failed to send message. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  if (isInitializing) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Initializing interview...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Header */}
      <div className="bg-white shadow-sm border-b px-4 py-4">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-xl font-semibold text-gray-900">
                Interview: {job.title}
              </h1>
              <p className="text-sm text-gray-600">
                Candidate: {candidateName} • {job.location || "Remote"}
              </p>
            </div>
            <div className="flex items-center space-x-2">
              <div className="w-3 h-3 bg-green-500 rounded-full"></div>
              <span className="text-sm text-gray-500">AI Agent Online</span>
            </div>
          </div>
        </div>
      </div>

      {/* Error Banner */}
      {error && (
        <div className="bg-red-50 border-b border-red-200 px-4 py-3">
          <div className="max-w-4xl mx-auto">
            <div className="flex items-center space-x-2">
              <svg className="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span className="text-red-800">{error}</span>
              <button
                onClick={() => setError('')}
                className="ml-auto text-red-600 hover:text-red-800"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Messages */}
      <div className="flex-1 overflow-y-auto px-4 py-6">
        <div className="max-w-4xl mx-auto space-y-6">
          {messages.map((message) => (
            <div
              key={message.id}
              className={`flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              <div
                className={`max-w-3xl px-6 py-4 rounded-2xl ${
                  message.sender === 'user'
                    ? 'bg-blue-600 text-white'
                    : 'bg-white text-gray-900 border border-gray-200'
                }`}
              >
                <div className="flex items-start space-x-3">
                  {message.sender === 'ai' && (
                    <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                      <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                      </svg>
                    </div>
                  )}
                  <div className="flex-1">
                    <p className="whitespace-pre-wrap">{message.content}</p>
                    <p className={`text-xs mt-2 ${
                      message.sender === 'user' ? 'text-blue-100' : 'text-gray-500'
                    }`}>
                      {formatTime(message.timestamp)}
                    </p>
                  </div>
                  {message.sender === 'user' && (
                    <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0">
                      <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                      </svg>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
          
          {isLoading && !isTyping && (
            <div className="flex justify-start">
              <div className="bg-white text-gray-900 border border-gray-200 rounded-2xl px-6 py-4">
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                    <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                  </div>
                  <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>
                </div>
              </div>
            </div>
          )}

          {isTyping && (
            <div className="flex justify-start">
              <div className="bg-white text-gray-900 border border-gray-200 rounded-2xl px-6 py-4">
                <div className="flex items-start space-x-3">
                  <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                  </div>
                  <div className="flex-1">
                    <p className="whitespace-pre-wrap">{typingMessage}</p>
                    <div className="flex items-center mt-2">
                      <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
          
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* Input */}
      <div className="bg-white border-t px-4 py-4">
        <div className="max-w-4xl mx-auto">
          <div className="flex space-x-4">
            <div className="flex-1">
              <textarea
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="Type your response here..."
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none text-gray-900 placeholder-gray-500 bg-white"
                rows={3}
                disabled={isLoading || isTyping}
              />
            </div>
            <button
              onClick={sendMessage}
              disabled={!inputMessage.trim() || isLoading || isTyping}
              className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isLoading ? (
                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
              ) : (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                </svg>
              )}
            </button>
          </div>
          <p className="text-xs text-gray-500 mt-2">
            Press Enter to send, Shift+Enter for new line
          </p>
        </div>
      </div>
    </div>
  );
}
