import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import KnowledgeCard from './KnowledgeCard';
import { useDispatch } from 'react-redux';
import { showNotification } from '../../store/notification.slice';
import SvgIcon from '../../components/SvgIcon';

export default function KnowledgeBase() {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [newKnowledgeBase, setNewKnowledgeBase] = useState({
        title: '',
        description: '',
    });

    const knowledgeList = [
        {
            id: '1',
            title: '产品开发知识库',
            description: '产品开发流程及规范说明文档',
            documents: 24,
            date: '2025-02-15',
            access: 'full',
        },
        {
            id: '2',
            title: '市场分析知识库',
            description: '2025年Q1市场分析总结',
            documents: 12,
            date: '2025-02-10',
            access: 'read',
        },
        {
            id: '3',
            title: '财务知识库',
            description: '月度财务分析报告',
            documents: 8,
            date: '2025-02-01',
            access: 'none',
        },
    ];

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setNewKnowledgeBase((prev) => ({
            ...prev,
            [name]: value,
        }));
    };

    const handleCreateKnowledgeBase = () => {
        // Here you would typically call an API to create the knowledge base
        if (!newKnowledgeBase.title.trim()) {
            dispatch(
                showNotification({
                    message: '请输入知识库名称',
                    type: 'error',
                })
            );
            return;
        }

        // For now, just show a success notification
        dispatch(
            showNotification({
                message: '知识库创建成功',
                type: 'success',
            })
        );

        // In a real application, you would get the ID from the API response
        // For now, we'll generate a mock ID
        const newId = Date.now().toString();

        // Reset form and close modal
        setNewKnowledgeBase({ title: '', description: '' });
        setShowCreateModal(false);

        // Navigate to the newly created knowledge base with datasets tab
        navigate(`/knowledge-base/${newId}/datasets`);
    };

    const handleCardClick = (id) => {
        navigate(`/knowledge-base/${id}/datasets`);
    };

    return (
        <div className='container'>
            <div className='d-flex justify-content-between align-items-center mb-3'>
                <input type='text' className='form-control w-50' placeholder='搜索知识库...' />
                <button
                    className='btn btn-dark d-flex align-items-center gap-1'
                    onClick={() => setShowCreateModal(true)}
                >
                    <SvgIcon className={'plus'} />
                    新建知识库
                </button>
            </div>

            <div className='row gap-3 m-0'>
                {knowledgeList.map((item) => (
                    <React.Fragment key={item.id}>
                        <KnowledgeCard {...item} onClick={() => handleCardClick(item.id)} />
                    </React.Fragment>
                ))}
            </div>

            {/* 新建知识库弹窗 */}
            {showCreateModal && (
                <div
                    className='modal-backdrop'
                    style={{
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        backgroundColor: 'rgba(0, 0, 0, 0.5)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        zIndex: 1050,
                    }}
                >
                    <div
                        className='modal-content bg-white rounded shadow'
                        style={{
                            width: '500px',
                            maxWidth: '90%',
                            padding: '20px',
                        }}
                    >
                        <div className='modal-header d-flex justify-content-between align-items-center mb-3'>
                            <h5 className='modal-title m-0'>新建知识库</h5>
                            <button
                                type='button'
                                className='btn-close'
                                onClick={() => setShowCreateModal(false)}
                                aria-label='Close'
                            ></button>
                        </div>
                        <div className='modal-body'>
                            <div className='mb-3'>
                                <label htmlFor='knowledgeTitle' className='form-label'>
                                    知识库名称
                                </label>
                                <input
                                    type='text'
                                    className='form-control'
                                    id='knowledgeTitle'
                                    name='title'
                                    value={newKnowledgeBase.title}
                                    onChange={handleInputChange}
                                    placeholder='请输入知识库名称'
                                    required
                                />
                            </div>
                            <div className='mb-3'>
                                <label htmlFor='knowledgeDescription' className='form-label'>
                                    知识库描述
                                </label>
                                <textarea
                                    className='form-control'
                                    id='knowledgeDescription'
                                    name='description'
                                    value={newKnowledgeBase.description}
                                    onChange={handleInputChange}
                                    placeholder='请输入知识库描述'
                                    rows='3'
                                ></textarea>
                            </div>
                        </div>
                        <div className='modal-footer d-flex justify-content-end gap-2'>
                            <button
                                type='button'
                                className='btn btn-outline-secondary'
                                onClick={() => setShowCreateModal(false)}
                            >
                                取消
                            </button>
                            <button type='button' className='btn btn-dark' onClick={handleCreateKnowledgeBase}>
                                创建
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
