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 { getKnowledgeBaseById } from '../../../store/knowledgeBase/knowledgeBase.thunks';
import SvgIcon from '../../../components/SvgIcon';
import DatasetTab from './DatasetTab';
import SettingsTab from './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 knowledgeBase = useSelector((state) => state.knowledgeBase.currentKnowledgeBase);
    const loading = useSelector((state) => state.knowledgeBase.loading);
    const error = useSelector((state) => state.knowledgeBase.error);

    // Fetch knowledge base details when component mounts or ID changes
    useEffect(() => {
        if (id) {
            dispatch(getKnowledgeBaseById(id));
        }
    }, [dispatch, id]);

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

    // If knowledge base not found, show notification and redirect
    useEffect(() => {
        if (!loading && error) {
            dispatch(
                showNotification({
                    message: `获取知识库失败: ${error.message || '未找到知识库'}`,
                    type: 'warning',
                })
            );
            navigate('/knowledge-base');
        }
    }, [loading, error, 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 (loading || !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>
    );
}
