import { useState, useRef, useEffect, useCallback } from 'react';
import { MessageCircle, X, Send, ChevronDown } from 'lucide-react';
import './Hippo.css';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  quickReplies?: string[];
}

interface HippoResponse {
  message: string;
  intent?: string;
  quickReplies?: string[];
  analysis?: {
    symptoms: Array<{ id: string; name_tr: string }>;
    diseases: Array<{ name_tr: string; urgency: string }>;
    doctor: { name: string; description: string } | null;
  };
}

const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';

export function Hippo() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showScrollButton, setShowScrollButton] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messagesContainerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  const handleScroll = useCallback(() => {
    if (!messagesContainerRef.current) return;
    const { scrollTop, scrollHeight, clientHeight } = messagesContainerRef.current;
    const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
    setShowScrollButton(!isNearBottom);
  }, []);

  // Alt+H keyboard shortcut to toggle chat
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.altKey && e.key.toLowerCase() === 'h') {
        e.preventDefault();
        setIsOpen(prev => !prev);
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  // Auto-focus input when chat opens
  useEffect(() => {
    if (isOpen) {
      // Small delay to allow the panel animation to start
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    }
  }, [isOpen]);

  useEffect(() => {
    if (messages.length > 0) {
      scrollToBottom();
    }
  }, [messages, scrollToBottom]);

  // Fetch greeting when chat opens
  useEffect(() => {
    if (isOpen && messages.length === 0) {
      fetchGreeting();
    }
  }, [isOpen, messages.length]);

  const fetchGreeting = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/hippo/greeting`);
      if (!response.ok) throw new Error('Failed to fetch greeting');
      const data: HippoResponse = await response.json();

      setMessages([{
        id: Date.now().toString(),
        role: 'assistant',
        content: data.message,
        quickReplies: data.quickReplies
      }]);
    } catch (error) {
      console.error('Error fetching greeting:', error);
      setMessages([{
        id: Date.now().toString(),
        role: 'assistant',
        content: "Hi! I'm HIPPO, your Hipograf health assistant.\n\nHow can I help?",
        quickReplies: ['Introduce Hipograf', 'Symptom guidance', 'Show pages']
      }]);
    }
  };

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

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: messageText.trim()
    };

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

    try {
      const history = messages.map(m => ({
        role: m.role,
        content: m.content
      }));

      const response = await fetch(`${API_BASE_URL}/hippo/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: messageText.trim(),
          history: history.slice(-6)
        })
      });

      if (!response.ok) throw new Error('Chat request failed');

      const data: HippoResponse = await response.json();

      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: data.message,
        quickReplies: data.quickReplies
      };

      setMessages(prev => [...prev, assistantMessage]);
    } catch (error) {
      console.error('Error sending message:', error);
      setMessages(prev => [...prev, {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: 'Something went wrong. Please try again.'
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    sendMessage(input);
  };

  const handleQuickReply = (reply: string) => {
    sendMessage(reply);
  };

  const toggleChat = () => {
    setIsOpen(prev => !prev);
  };

  return (
    <div className="hippo-container">
      {/* Chat Panel */}
      <div className={`hippo-panel ${isOpen ? 'hippo-panel-open' : ''}`}>
        {/* Header */}
        <div className="hippo-header">
          <div className="hippo-header-info">
            <div className="hippo-avatar">H</div>
            <div>
              <h3 className="hippo-title">HIPPO</h3>
              <p className="hippo-subtitle">Hipograf Health Assistant</p>
            </div>
          </div>
          <button onClick={toggleChat} className="hippo-close-btn" aria-label="Close">
            <X size={20} />
          </button>
        </div>

        {/* Messages */}
        <div
          className="hippo-messages"
          ref={messagesContainerRef}
          onScroll={handleScroll}
        >
          {messages.map((message) => (
            <div
              key={message.id}
              className={`hippo-message ${message.role === 'user' ? 'hippo-message-user' : 'hippo-message-assistant'}`}
            >
              <div className={`hippo-bubble ${message.role === 'user' ? 'hippo-bubble-user' : 'hippo-bubble-assistant'}`}>
                {message.content.split('\n').map((line, i) => (
                  <span key={i}>
                    {line}
                    {i < message.content.split('\n').length - 1 && <br />}
                  </span>
                ))}
              </div>

              {/* Quick Replies */}
              {message.role === 'assistant' && message.quickReplies && message.quickReplies.length > 0 && (
                <div className="hippo-quick-replies">
                  {message.quickReplies.map((reply, index) => (
                    <button
                      key={index}
                      onClick={() => handleQuickReply(reply)}
                      className="hippo-quick-reply"
                      disabled={isLoading}
                    >
                      {reply}
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}

          {/* Loading indicator */}
          {isLoading && (
            <div className="hippo-message hippo-message-assistant">
              <div className="hippo-bubble hippo-bubble-assistant hippo-typing">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          )}

          <div ref={messagesEndRef} />
        </div>

        {/* Scroll to bottom button */}
        {showScrollButton && (
          <button
            onClick={scrollToBottom}
            className="hippo-scroll-btn"
            aria-label="Scroll to bottom"
          >
            <ChevronDown size={20} />
          </button>
        )}

        {/* Input */}
        <form onSubmit={handleSubmit} className="hippo-input-form">
          <input
            type="text"
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Type your message..."
            className="hippo-input"
            disabled={isLoading}
          />
          <button
            type="submit"
            disabled={!input.trim() || isLoading}
            className="hippo-send-btn"
            aria-label="Send"
          >
            <Send size={18} />
          </button>
        </form>
      </div>

      {/* Floating Button */}
      <button
        onClick={toggleChat}
        className={`hippo-fab ${isOpen ? 'hippo-fab-hidden' : ''}`}
        aria-label="Open HIPPO assistant"
      >
        <MessageCircle size={24} />
      </button>
    </div>
  );
}

export default Hippo;
