import React, { useState, useEffect, useRef, useCallback } from 'react';
import { MessageSquare, Activity, ChevronRight, Plus } from 'lucide-react';
import apiClient from '../../api/client';
import type { ChatSession, Message } from '../../App';
import type { ChatMessageDB } from '../../types';

interface ChatPanelProps {
  chatSessions: ChatSession[];
  setChatSessions: React.Dispatch<React.SetStateAction<ChatSession[]>>;
  activeSessionId: string | null;
  setActiveSessionId: React.Dispatch<React.SetStateAction<string | null>>;
  onSessionsChanged?: () => void;
}

export function ChatPanel({ chatSessions, setChatSessions, activeSessionId, setActiveSessionId, onSessionsChanged }: ChatPanelProps) {
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [mode, setMode] = useState<'chat' | 'deploy'>('chat');
  const [loadingMessages, setLoadingMessages] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const activeSession = chatSessions.find((s) => s.id === activeSessionId) || null;
  const messages = activeSession ? activeSession.messages : [];

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

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

  const loadMessages = useCallback(async (chatId: string) => {
    setLoadingMessages(true);
    try {
      const response = await apiClient.get(`/api/v1/chat/${chatId}`);
      const dbMessages: ChatMessageDB[] = response.data?.messages || [];
      const mapped: Message[] = dbMessages.map((m) => ({
        id: m.message_id,
        role: m.message_owner === 'user' ? 'user' : 'assistant',
        content: m.message,
        timestamp: new Date(m.created_at).getTime(),
      }));
      setChatSessions((prev) =>
        prev.map((s) => (s.id === chatId ? { ...s, messages: mapped } : s))
      );
    } catch (error) {
      console.error('Failed to load messages', error);
    } finally {
      setLoadingMessages(false);
    }
  }, [setChatSessions]);

  useEffect(() => {
    if (activeSessionId) {
      const session = chatSessions.find((s) => s.id === activeSessionId);
      if (session && session.messages.length === 0) {
        loadMessages(activeSessionId);
      }
    }
  }, [activeSessionId]);

  const updateSessionMessages = (newMessages: Message[]) => {
    if (!activeSessionId) return;
    setChatSessions((prev) =>
      prev.map((s) =>
        s.id === activeSessionId
          ? { ...s, messages: newMessages, updatedAt: Date.now() }
          : s
      )
    );
  };

  const handleNewChat = async () => {
    if (!onSessionsChanged) return;
    try {
      const response = await apiClient.post('/api/v1/chat', {
        title: '新对话',
        initial_message: '你好',
      });
      const chatId: string = response.data.chat_id;
      const reply: string = response.data.reply || '你好！我是 kilostar 助手，有什么可以帮你的吗？';

      const newSession: ChatSession = {
        id: chatId,
        title: '新对话',
        messages: [
          { id: chatId + '_user', role: 'user', content: '你好', timestamp: Date.now() },
          { id: chatId + '_ai', role: 'assistant', content: reply, timestamp: Date.now() },
        ],
        updatedAt: Date.now(),
      };
      setChatSessions((prev) => [newSession, ...prev]);
      setActiveSessionId(chatId);
      onSessionsChanged();
    } catch (error) {
      console.error('Failed to create chat session', error);
    }
  };

  const handleSendMessage = async () => {
    if (!input.trim() || !activeSessionId) return;

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

    const currentMessages = activeSession?.messages || [];
    updateSessionMessages([...currentMessages, userMessage]);
    setInput('');
    setLoading(true);

    try {
      const response = await apiClient.post(`/api/v1/chat/${activeSessionId}/reply`, {
        message: userText,
      });

      const replyContent: string = response.data?.reply || '收到你的消息。';

      if (currentMessages.length <= 1 && userText.length > 0) {
        setChatSessions((prev) =>
          prev.map((s) =>
            s.id === activeSessionId
              ? { ...s, title: userText.slice(0, 20) + (userText.length > 20 ? '...' : '') }
              : s
          )
        );
      }

      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: replyContent,
        timestamp: Date.now(),
      };

      const updatedMessages = [...(currentMessages.length > 0 ? currentMessages : []), userMessage, aiMessage];
      updateSessionMessages(updatedMessages);
    } catch (error) {
      console.error('Error sending message', error);
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: '抱歉，与服务器通信时出错。',
        timestamp: Date.now(),
      };
      updateSessionMessages([...currentMessages, userMessage, errorMessage]);
    } finally {
      setLoading(false);
    }
  };

  if (!activeSessionId) {
    return (
      <div className="flex-1 flex flex-col bg-white overflow-hidden items-center justify-center">
        <Activity size={48} className="text-slate-300 mb-4" />
        <h2 className="text-xl font-semibold text-slate-600">kilostar Assistant</h2>
        <p className="text-slate-400 mt-2">Select a chat history or create a new one to start.</p>
        <button
          onClick={handleNewChat}
          className="mt-6 px-6 py-2 bg-blue-200 text-slate-800 rounded-xl shadow-sm hover:bg-blue-300 transition-colors"
        >
          Start New Chat
        </button>
      </div>
    );
  }

  return (
    <div className="flex-1 flex flex-col bg-white overflow-hidden relative">
      <div className="h-14 border-b border-slate-100 bg-white flex items-center justify-between px-6 z-10 shrink-0">
        <div className="flex items-center">
          <MessageSquare size={18} className="text-blue-600 mr-3" />
          <h1 className="font-semibold text-slate-800">{activeSession?.title || 'Chat'}</h1>
        </div>
        <div className="flex space-x-2 bg-slate-50 p-1 rounded-lg">
          <button
            onClick={() => setMode('chat')}
            className={`px-3 py-1 text-sm font-medium rounded-md transition-colors ${
              mode === 'chat' ? 'bg-white text-blue-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'
            }`}
          >
            Chat
          </button>
          <button
            onClick={() => setMode('deploy')}
            className={`px-3 py-1 text-sm font-medium rounded-md transition-colors ${
              mode === 'deploy' ? 'bg-white text-blue-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'
            }`}
          >
            Deploy Task
          </button>
        </div>
      </div>

      <div className="flex-1 p-6 overflow-y-auto space-y-6 bg-white">
        {loadingMessages ? (
          <div className="flex justify-center items-center h-full">
            <div className="flex space-x-2">
              <span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce"></span>
              <span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce delay-75"></span>
              <span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce delay-150"></span>
            </div>
          </div>
        ) : (
          messages.map((msg) => (
            <div key={msg.id} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
              {msg.role === 'assistant' && (
                <div className="w-8 h-8 rounded-full bg-white border border-blue-100 flex items-center justify-center mr-3 mt-1 shadow-sm flex-shrink-0">
                  <Activity size={16} className="text-blue-600" />
                </div>
              )}
              <div
                className={`${
                  msg.role === 'user'
                    ? 'bg-blue-100 text-slate-800 rounded-2xl rounded-tr-sm'
                    : 'bg-slate-50 border border-slate-100 text-slate-700 rounded-2xl rounded-tl-sm'
                } p-4 max-w-[80%] shadow-sm`}
              >
                <p className="text-sm leading-relaxed mb-1 whitespace-pre-wrap">{msg.content}</p>
              </div>
            </div>
          ))
        )}
        {loading && (
          <div className="flex justify-start">
            <div className="w-8 h-8 rounded-full bg-white border border-blue-100 flex items-center justify-center mr-3 mt-1 shadow-sm flex-shrink-0">
              <Activity size={16} className="text-blue-600 animate-spin" />
            </div>
            <div className="bg-slate-50 border border-slate-100 text-slate-700 p-4 rounded-2xl rounded-tl-sm max-w-[80%] shadow-sm">
              <span className="flex space-x-1">
                <span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce"></span>
                <span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce delay-75"></span>
                <span className="h-2 w-2 bg-slate-400 rounded-full animate-bounce delay-150"></span>
              </span>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="p-4 bg-white border-t border-slate-100 shrink-0">
        <div className="relative flex items-center">
          <input type="file" ref={fileInputRef} className="hidden" />
          <button
            onClick={() => fileInputRef.current?.click()}
            className="absolute left-2 p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors z-10 cursor-pointer"
            title="Add attachment"
          >
            <Plus size={20} />
          </button>
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
            placeholder="Ask kilostar to do something..."
            className="w-full bg-slate-50 border border-slate-200 text-sm rounded-2xl pl-12 pr-12 py-3.5 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 transition-all"
          />
          <button
            onClick={handleSendMessage}
            disabled={loading || !input.trim()}
            className="absolute right-2 p-1.5 bg-blue-200 text-slate-800 rounded-xl hover:bg-blue-300 transition-colors shadow-sm disabled:opacity-50 cursor-pointer"
          >
            <ChevronRight size={18} />
          </button>
        </div>
      </div>
    </div>
  );
}
