import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import ChatSidebar from './ChatSidebar';
import NewChat from './NewChat';
import ChatWindow from './ChatWindow';

export default function Chat() {
    const { knowledgeBaseId, chatId } = useParams();
    const navigate = useNavigate();
    const [chatHistory, setChatHistory] = useState([
        {
            id: '1',
            knowledgeBaseId: '1',
            title: 'Chat History 1',
            lastMessage: '上次聊天内容的摘要...',
            timestamp: '2025-01-20T10:30:00Z',
        },
        {
            id: '2',
            knowledgeBaseId: '2',
            title: 'Chat History 2',
            lastMessage: '上次聊天内容的摘要...',
            timestamp: '2025-01-19T14:45:00Z',
        },
    ]);

    // If we have a knowledgeBaseId but no chatId, create a new chat
    useEffect(() => {
        if (knowledgeBaseId && !chatId) {
            // In a real app, you would create a new chat and get its ID from the API
            const newChatId = Date.now().toString();
            navigate(`/chat/${knowledgeBaseId}/${newChatId}`);
        }
    }, [knowledgeBaseId, chatId, navigate]);

    const handleDeleteChat = (id) => {
        // In a real app, you would call an API to delete the chat
        setChatHistory((prevHistory) => prevHistory.filter((chat) => chat.id !== id));

        // If the deleted chat is the current one, navigate to the chat list
        if (chatId === id) {
            navigate('/chat');
        }
    };

    return (
        <div className='chat-container container-fluid h-100'>
            <div className='row h-100'>
                {/* Sidebar */}
                <div
                    className='col-md-3 col-lg-2 p-0 border-end'
                    style={{ height: 'calc(100vh - 73px)', overflowY: 'auto' }}
                >
                    <ChatSidebar chatHistory={chatHistory} onDeleteChat={handleDeleteChat} />
                </div>

                {/* Main Content */}
                <div
                    className='chat-main col-md-9 col-lg-10 p-0'
                    style={{ height: 'calc(100vh - 73px)', overflowY: 'auto' }}
                >
                    {!chatId ? <NewChat /> : <ChatWindow chatId={chatId} knowledgeBaseId={knowledgeBaseId} />}
                </div>
            </div>
        </div>
    );
}
