import React, { useState, useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchMessages, sendMessage } from '../../store/chat/chat.messages.thunks';
import { resetMessages, resetSendMessageStatus, addMessage } from '../../store/chat/chat.slice';
import { showNotification } from '../../store/notification.slice';
import SvgIcon from '../../components/SvgIcon';
import { fetchKnowledgeBases } from '../../store/knowledgeBase/knowledgeBase.thunks';

export default function ChatWindow({ chatId, knowledgeBaseId }) {
    const dispatch = useDispatch();
    const [inputMessage, setInputMessage] = useState('');
    const messagesEndRef = useRef(null);

    // 从 Redux store 获取数据
    const {
        items: messages,
        status: messagesStatus,
        error: messagesError,
    } = useSelector((state) => state.chat.messages);
    const { status: sendStatus, error: sendError } = useSelector((state) => state.chat.sendMessage);
    const knowledgeBase = useSelector((state) =>
        state.knowledgeBase.list.data?.items?.find((kb) => kb.id === knowledgeBaseId)
    );
    const isLoadingKnowledgeBases = useSelector((state) => state.knowledgeBase.list.isLoading);

    // 获取聊天消息
    useEffect(() => {
        if (chatId) {
            dispatch(fetchMessages(chatId));
        }

        // 组件卸载时重置消息状态
        return () => {
            dispatch(resetMessages());
        };
    }, [chatId, dispatch]);

    // 监听发送消息状态
    useEffect(() => {
        if (sendStatus === 'failed' && sendError) {
            dispatch(
                showNotification({
                    message: `发送失败: ${sendError}`,
                    type: 'danger',
                })
            );
            dispatch(resetSendMessageStatus());
        }
    }, [sendStatus, sendError, dispatch]);

    // 滚动到底部
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    // 从 Redux store 获取知识库信息
    useEffect(() => {
        if (!knowledgeBase && !isLoadingKnowledgeBases) {
            dispatch(fetchKnowledgeBases());
        }
    }, [dispatch, knowledgeBase, isLoadingKnowledgeBases]);

    const handleSendMessage = (e) => {
        e.preventDefault();

        if (!inputMessage.trim() || sendStatus === 'loading') return;

        // 立即添加用户消息到界面
        const userMessage = {
            id: Date.now(),
            content: inputMessage,
            sender: 'user',
            timestamp: new Date().toISOString(),
        };
        dispatch(addMessage(userMessage));

        // 清空输入框
        setInputMessage('');

        // 发送消息到服务器
        dispatch(sendMessage({ chatId, content: inputMessage }));
    };

    // 渲染加载状态
    const renderLoading = () => (
        <div className='p-5 text-center'>
            <div className='spinner-border text-secondary' role='status'>
                <span className='visually-hidden'>加载中...</span>
            </div>
            <div className='mt-3 text-muted'>加载聊天记录...</div>
        </div>
    );

    // 渲染错误状态
    const renderError = () => (
        <div className='p-5 text-center'>
            <div className='text-danger mb-3'>
                <SvgIcon className='error' width='48' height='48' />
            </div>
            <div className='text-muted'>加载聊天记录失败，请重试</div>
            <button className='btn btn-outline-secondary mt-3' onClick={() => dispatch(fetchMessages(chatId))}>
                重新加载
            </button>
        </div>
    );

    // 渲染空状态
    const renderEmpty = () => (
        <div className='p-5 text-center'>
            <div className='text-muted'>暂无聊天记录，发送一条消息开始聊天吧</div>
        </div>
    );

    return (
        <div className='chat-window d-flex flex-column h-100'>
            {/* Chat header */}
            <div className='p-3 border-bottom'>
                <h5 className='mb-0'>{knowledgeBase?.name || '加载中...'}</h5>
                <small className='text-muted'>{knowledgeBase?.description}</small>
            </div>

            {/* Chat messages */}
            <div className='flex-grow-1 p-3 overflow-auto'>
                <div className='container'>
                    {messagesStatus === 'loading'
                        ? renderLoading()
                        : messagesStatus === 'failed'
                        ? renderError()
                        : messages.length === 0
                        ? renderEmpty()
                        : messages.map((message) => (
                              <div
                                  key={message.id}
                                  className={`d-flex ${
                                      message.sender === 'user' ? 'justify-content-end' : 'justify-content-start'
                                  } mb-3`}
                              >
                                  <div
                                      className={`chat-message p-3 rounded-3 ${
                                          message.sender === 'user' ? 'bg-dark text-white' : 'bg-light'
                                      }`}
                                      style={{
                                          maxWidth: '75%',
                                          position: 'relative',
                                      }}
                                  >
                                      <div className='message-content'>{message.content}</div>
                                  </div>
                              </div>
                          ))}

                    {sendStatus === 'loading' && (
                        <div className='d-flex justify-content-start mb-3'>
                            <div className='chat-message p-3 rounded-3 bg-light'>
                                <div className='spinner-border spinner-border-sm text-secondary' role='status'>
                                    <span className='visually-hidden'>加载中...</span>
                                </div>
                            </div>
                        </div>
                    )}

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

            {/* Chat input */}
            <div className='p-3 border-top'>
                <form onSubmit={handleSendMessage} className='d-flex gap-2'>
                    <input
                        type='text'
                        className='form-control'
                        placeholder='输入你的问题...'
                        value={inputMessage}
                        onChange={(e) => setInputMessage(e.target.value)}
                        disabled={sendStatus === 'loading'}
                    />
                    <button
                        type='submit'
                        className='btn btn-dark d-flex align-items-center justify-content-center gap-2'
                        disabled={sendStatus === 'loading' || !inputMessage.trim()}
                    >
                        <SvgIcon className='send' color='#ffffff' />
                        <span className='ms-1' style={{ minWidth: 'fit-content' }}>
                            发送
                        </span>
                    </button>
                </form>
            </div>
        </div>
    );
}
