import { useState, useEffect, useMemo } from 'react';
import {
    useAnalysisTemplateSets,
    updateAnalysisTemplateSets,
    useLlmProviders
} from '@/hooks/useApi';
import { AnalysisTemplateSets, LlmModel } from '@/types';

export function useAnalysisConfig() {
    const { data: initialAnalysisTemplateSets, mutate: mutateAnalysisTemplateSets } = useAnalysisTemplateSets();
    const { data: llmProviders } = useLlmProviders();

    const [localTemplateSets, setLocalTemplateSets] = useState<AnalysisTemplateSets>({});
    const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);
    
    const [isSavingAnalysis, setIsSavingAnalysis] = useState(false);
    const [analysisSaveMessage, setAnalysisSaveMessage] = useState('');

    const [newTemplateId, setNewTemplateId] = useState('');
    const [newTemplateName, setNewTemplateName] = useState('');
    const [isCreatingTemplate, setIsCreatingTemplate] = useState(false);

    const [isCreatingModule, setIsCreatingModule] = useState(false);
    const [newModuleId, setNewModuleId] = useState('');
    const [newModuleName, setNewModuleName] = useState('');

    const allModels = useMemo(() => {
        if (!llmProviders) return [];
        const models: { providerId: string; providerName: string; model: LlmModel }[] = [];
        Object.entries(llmProviders).forEach(([pId, provider]) => {
            provider.models.forEach(m => {
                 if (m.is_active) {
                     models.push({
                         providerId: pId,
                         providerName: provider.name || pId,
                         model: m
                     });
                 }
            });
        });
        return models;
    }, [llmProviders]);

    useEffect(() => {
        if (!initialAnalysisTemplateSets) return;
        setLocalTemplateSets(initialAnalysisTemplateSets);
        // 仅在未选择时，从后端数据中选择第一个模板；避免覆盖本地新增的选择与状态
        setSelectedTemplateId(prev => prev ?? (Object.keys(initialAnalysisTemplateSets)[0] || null));
    }, [initialAnalysisTemplateSets]);

    const handleAnalysisChange = (moduleId: string, field: string, value: any) => {
        if (!selectedTemplateId) return;
        setLocalTemplateSets(prev => ({
            ...prev,
            [selectedTemplateId]: {
                ...prev[selectedTemplateId],
                modules: {
                    ...prev[selectedTemplateId].modules,
                    [moduleId]: {
                        ...prev[selectedTemplateId].modules[moduleId],
                        [field]: value,
                    },
                },
            },
        }));
    };

    const handleSaveAnalysis = async () => {
        setIsSavingAnalysis(true);
        setAnalysisSaveMessage('保存中...');
        try {
            const updated = await updateAnalysisTemplateSets(localTemplateSets);
            await mutateAnalysisTemplateSets(updated, false);
            setAnalysisSaveMessage('分析配置保存成功!');
        } catch (e: any) {
            setAnalysisSaveMessage(`保存失败: ${e.message}`);
        } finally {
            setIsSavingAnalysis(false);
            setTimeout(() => setAnalysisSaveMessage(''), 5000);
        }
    };

    const updateAnalysisDependencies = (moduleId: string, dependency: string, checked: boolean) => {
        if (!selectedTemplateId) return;
        setLocalTemplateSets(prev => {
            const currentModule = prev[selectedTemplateId].modules[moduleId];
            const currentDeps = currentModule.dependencies || [];
            const newDeps = checked
                ? [...currentDeps, dependency]
                : currentDeps.filter(d => d !== dependency);

            return {
                ...prev,
                [selectedTemplateId]: {
                    ...prev[selectedTemplateId],
                    modules: {
                        ...prev[selectedTemplateId].modules,
                        [moduleId]: {
                            ...currentModule,
                            dependencies: [...new Set(newDeps)],
                        },
                    },
                },
            };
        });
    };

    const handleAddTemplate = async () => {
         if (!newTemplateId || !newTemplateName) {
            setAnalysisSaveMessage('模板 ID 和名称不能为空');
            return;
        }
        if (localTemplateSets[newTemplateId]) {
            setAnalysisSaveMessage('模板 ID 已存在');
            return;
        }
        const newSet: AnalysisTemplateSets = {
            ...localTemplateSets,
            [newTemplateId]: {
                name: newTemplateName,
                modules: {},
            },
        };
        setLocalTemplateSets(newSet);
        setSelectedTemplateId(newTemplateId);
        setNewTemplateId('');
        setNewTemplateName('');
        setIsCreatingTemplate(false);
        
        // 新建后立即持久化
        setIsSavingAnalysis(true);
        setAnalysisSaveMessage('保存中...');
        try {
            const updated = await updateAnalysisTemplateSets(newSet);
            await mutateAnalysisTemplateSets(updated, false);
            setAnalysisSaveMessage('分析配置保存成功!');
        } catch (e: any) {
            setAnalysisSaveMessage(`保存失败: ${e?.message || '未知错误'}`);
        } finally {
            setIsSavingAnalysis(false);
            setTimeout(() => setAnalysisSaveMessage(''), 5000);
        }
    };

    const handleDeleteTemplate = () => {
        if (!selectedTemplateId || !localTemplateSets[selectedTemplateId]) return;
        if (!window.confirm(`确定要删除模板 "${localTemplateSets[selectedTemplateId].name}" 吗？`)) {
            return;
        }
        const newSets = { ...localTemplateSets };
        delete newSets[selectedTemplateId];
        setLocalTemplateSets(newSets);
        const firstKey = Object.keys(newSets)[0] || null;
        setSelectedTemplateId(firstKey);
    };

    const handleAddNewModule = () => {
        if (!selectedTemplateId || !newModuleId || !newModuleName) {
            setAnalysisSaveMessage('模块 ID 和名称不能为空');
            return;
        }
        if (localTemplateSets[selectedTemplateId].modules[newModuleId]) {
            setAnalysisSaveMessage('模块 ID 已存在');
            return;
        }
        setLocalTemplateSets(prev => ({
            ...prev,
            [selectedTemplateId]: {
                ...prev[selectedTemplateId],
                modules: {
                    ...prev[selectedTemplateId].modules,
                    [newModuleId]: {
                        name: newModuleName,
                        provider_id: '',
                        model_id: '',
                        prompt_template: '',
                        dependencies: [],
                    }
                }
            }
        }));
        setNewModuleId('');
        setNewModuleName('');
        setIsCreatingModule(false);
    };

    const handleDeleteModule = (moduleId: string) => {
        if (!selectedTemplateId) return;
        setLocalTemplateSets(prev => {
            const newModules = { ...prev[selectedTemplateId].modules };
            delete newModules[moduleId];
            return {
                ...prev,
                [selectedTemplateId]: {
                    ...prev[selectedTemplateId],
                    modules: newModules,
                },
            };
        });
    };

    return {
        localTemplateSets,
        selectedTemplateId,
        setSelectedTemplateId,
        allModels,
        isSavingAnalysis,
        analysisSaveMessage,
        setAnalysisSaveMessage,
        // Template creation
        newTemplateId, setNewTemplateId,
        newTemplateName, setNewTemplateName,
        isCreatingTemplate, setIsCreatingTemplate,
        handleAddTemplate,
        handleDeleteTemplate,
        // Module creation
        isCreatingModule, setIsCreatingModule,
        newModuleId, setNewModuleId,
        newModuleName, setNewModuleName,
        handleAddNewModule,
        handleDeleteModule,
        // Actions
        handleAnalysisChange,
        handleSaveAnalysis,
        updateAnalysisDependencies
    };
}

