import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { showNotification } from '../../store/notification.slice';
import SvgIcon from '../../components/SvgIcon';
import DatasetTab from './Detail/DatasetTab';
import SettingsTab from './Detail/SettingsTab';

export default function KnowledgeBaseDetail() {
    const { id, tab } = useParams();
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [activeTab, setActiveTab] = useState(tab === 'settings' ? 'settings' : 'datasets');

    // Get knowledge base details from Redux store
    const { items: knowledgeBases } = useSelector((state) => state.knowledgeBase.list);
    const knowledgeBase = knowledgeBases.find((kb) => kb.id === id);

    // Update active tab when URL changes
    useEffect(() => {
        if (tab) {
            setActiveTab(tab === 'settings' ? 'settings' : 'datasets');
        }
    }, [tab]);

    // If knowledge base not found in Redux store, show notification and redirect
    useEffect(() => {
        if (!knowledgeBase && knowledgeBases.length > 0) {
            dispatch(
                showNotification({
                    message: '未找到知识库，请返回知识库列表',
                    type: 'warning',
                })
            );
            navigate('/knowledge-base');
        }
    }, [knowledgeBase, knowledgeBases, dispatch, navigate]);

    // Handle tab change
    const handleTabChange = (tab) => {
        setActiveTab(tab);
        navigate(`/knowledge-base/${id}/${tab}`);
    };

    // Show loading state if knowledge base not loaded yet
    if (!knowledgeBase) {
        return (
            <div className='container-fluid px-4 py-5 text-center'>
                <div className='spinner-border' role='status'>
                    <span className='visually-hidden'>加载中...</span>
                </div>
            </div>
        );
    }

    return (
        <div className='container-fluid px-4'>
            <div className='row'>
                {/* Sidebar */}
                <div className='col-md-3 col-lg-2 border-end'>
                    <div className='py-4'>
                        <div className='h4 mb-3 text-center'>{knowledgeBase.name}</div>
                        <p className='text-center text-muted small mb-4'>{knowledgeBase.desc}</p>

                        <hr />

                        <nav className='nav flex-column'>
                            <a
                                className={`nav-link link-dark link-underline-light d-flex align-items-center gap-2 ${
                                    activeTab === 'datasets' ? 'active bg-light rounded fw-bold' : ''
                                }`}
                                href='#'
                                onClick={(e) => {
                                    e.preventDefault();
                                    handleTabChange('datasets');
                                }}
                            >
                                <SvgIcon className='dataset' />
                                数据集
                            </a>
                            <a
                                className={`nav-link link-dark link-underline-light d-flex align-items-center gap-1 ${
                                    activeTab === 'settings' ? 'active bg-light rounded fw-bold' : ''
                                }`}
                                href='#'
                                onClick={(e) => {
                                    e.preventDefault();
                                    handleTabChange('settings');
                                }}
                            >
                                <SvgIcon className='setting-fill' />
                                设置
                            </a>
                        </nav>
                    </div>
                </div>

                {/* Main content */}
                <div className='col-md-9 col-lg-10'>
                    {/* Render the appropriate tab component */}
                    {activeTab === 'datasets' ? (
                        <DatasetTab knowledgeBase={knowledgeBase} />
                    ) : (
                        <SettingsTab knowledgeBase={knowledgeBase} />
                    )}
                </div>
            </div>
        </div>
    );
}
