import { Spin } from 'antd';
import DatasetLayout from './layout';
import DocumentList from './document-list';
import DocumentDetail from './document-detail';
import RetrieveTest from './retrieve-test';
import DatasetSettings from './dataset-settings';
import AreaDatasetConfig from './area-dataset-config';
import { useDatasetManager } from '~/hooks/dify-dataset-manager';
import { usePermission } from '~/hooks/usePermission';
import '../../styles/components/dify-dataset-manager/index.css';

/**
 * 知识库管理主组件
 * 带左侧菜单栏的完整布局
 */
export default function DatasetManager() {
    const {
        // 状态
        dataset,
        loadingDataset,
        documents,
        loadingDocuments,
        documentTotal,
        documentPage,
        documentPageSize,
        inited,
        error,
        activeTab,
        selectedDocument,

        // 知识库列表（基于权限）
        availableDatasets,
        loadingAvailableDatasets,

        // 方法
        handlePageChange,
        handleDocumentDeleted,
        handleDocumentStatusChanged,
        handleRefresh,
        handleViewDocument,
        handleBackToDocuments,
        handleTabChange,
        handleDatasetUpdated,
        handleDatasetChange,
    } = useDatasetManager();

    // 判断当前用户是否能编辑当前知识库（省级管理员可编辑全部，市级管理员只能编辑本地区）
    const { userRole, userArea } = usePermission();
    const canEditDataset = userRole === 'provincial_admin' || ((dataset as any)?.area === userArea);

    // 加载中状态
    if (!inited || loadingDataset) {
        return (
            <div className="dataset-manager-wrapper">
                <div className="dataset-loading-state">
                    <Spin size="large" />
                    <span className="loading-text">正在加载知识库...</span>
                </div>
            </div>
        );
    }

    // 错误状态
    if (error) {
        return (
            <div className="dataset-manager-wrapper">
                <div className="dataset-error-state">
                    <i className="ri-error-warning-line error-icon"></i>
                    <h3>加载失败</h3>
                    <p>{error}</p>
                </div>
            </div>
        );
    }

    /**
     * 渲染右侧内容区
     */
    const renderContent = () => {
        // 文档菜单
        if (activeTab === 'documents') {
            // 如果选中了文档，显示文档详情
            if (selectedDocument) {
                return (
                    <DocumentDetail
                        datasetId={dataset?.id || ''}
                        document={selectedDocument}
                        canEditDataset={canEditDataset}
                    />
                );
            }
            // 否则显示文档列表
            return (
                <DocumentList
                    datasetId={dataset?.id || ''}
                    datasetName={dataset?.name || ''}
                    documents={documents}
                    loading={loadingDocuments}
                    total={documentTotal}
                    page={documentPage}
                    pageSize={documentPageSize}
                    onPageChange={handlePageChange}
                    onDocumentDeleted={handleDocumentDeleted}
                    onDocumentStatusChanged={handleDocumentStatusChanged}
                    onRefresh={handleRefresh}
                    onViewDocument={handleViewDocument}
                    canEditDataset={canEditDataset}
                />
            );
        }

        // 召回测试菜单
        if (activeTab === 'retrieve') {
            return <RetrieveTest datasetId={dataset?.id || ''} />;
        }

        // 配置管理菜单
        if (activeTab === 'area-config') {
            return <AreaDatasetConfig />;
        }

        // 设置菜单
        if (activeTab === 'settings') {
            return (
                <DatasetSettings
                    dataset={dataset}
                    onDatasetUpdated={handleDatasetUpdated}
                    canEditDataset={canEditDataset}
                />
            );
        }

        return null;
    };

    return (
        <div className="dataset-manager-wrapper">
            <DatasetLayout
                dataset={dataset}
                activeTab={activeTab}
                onTabChange={handleTabChange}
                showBackButton={activeTab === 'documents' && !!selectedDocument}
                onBack={handleBackToDocuments}
                availableDatasets={availableDatasets}
                loadingAvailableDatasets={loadingAvailableDatasets}
                onDatasetChange={handleDatasetChange}
            >
                {renderContent()}
            </DatasetLayout>
        </div>
    );
}
