import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { fetchChats, deleteChat } from '../../store/chat/chat.thunks';
import { showNotification } from '../../store/notification.slice';
import ChatSidebar from './ChatSidebar';
import NewChat from './NewChat';
import ChatWindow from './ChatWindow';

export default function Chat() {
    const { knowledgeBaseId, chatId } = useParams();
    const navigate = useNavigate();
    const dispatch = useDispatch();

    // 从 Redux store 获取聊天记录列表
    const { items: chatHistory, status, error } = useSelector((state) => state.chat.list);
    const operationStatus = useSelector((state) => state.chat.operations.status);
    const operationError = useSelector((state) => state.chat.operations.error);

    // 获取聊天记录列表
    useEffect(() => {
        dispatch(fetchChats());
    }, [dispatch]);

    // 监听操作状态，显示通知
    useEffect(() => {
        if (operationStatus === 'succeeded') {
            dispatch(
                showNotification({
                    message: '操作成功',
                    type: 'success',
                })
            );
        } else if (operationStatus === 'failed' && operationError) {
            dispatch(
                showNotification({
                    message: `操作失败: ${operationError}`,
                    type: 'danger',
                })
            );
        }
    }, [operationStatus, operationError, dispatch]);

    // 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) => {
        // 调用 Redux action 删除聊天
        dispatch(deleteChat(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}
                        isLoading={status === 'loading'}
                        hasError={status === 'failed'}
                    />
                </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>
    );
}
