
import { useState, useEffect, useMemo } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Separator } from "@/components/ui/separator";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { ModelSelector } from './ModelSelector';
import { useAnalysisTemplateSets, updateAnalysisTemplateSets, useLlmProviders } from '@/hooks/useApi';
import type { AnalysisTemplateSets, LlmModel } from '@/types';

export function AnalysisConfigTab() {
  // LLM Providers for Model Selector
  const { data: llmProviders } = useLlmProviders();
  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]);

  // Analysis Config State
  const { data: initialAnalysisTemplateSets, mutate: mutateAnalysisTemplateSets } = useAnalysisTemplateSets();
  const [localTemplateSets, setLocalTemplateSets] = useState<AnalysisTemplateSets>({});
  const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);

  const [isSavingAnalysis, setIsSavingAnalysis] = useState(false);
  const [analysisSaveMessage, setAnalysisSaveMessage] = useState('');

  // State for creating/editing templates and modules
  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('');

  // Initialize local state
  useEffect(() => {
      if (!initialAnalysisTemplateSets) return;
      setLocalTemplateSets(initialAnalysisTemplateSets);
      // Only set if null (first load), to avoid resetting user selection on revalidation
      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 = () => {
      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);
      // 新建后立即持久化
      (async () => {
        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 || !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 (
    <Card>
      <CardHeader>
        <CardTitle>分析模板与模块配置</CardTitle>
        <CardDescription>管理不同的分析模板集，并为每个模板集内的模块配置模型、提示词和依赖关系。</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">

        {/* --- Level 1: Template Set Management --- */}
        <div className="p-4 border rounded-lg bg-slate-50 space-y-4">
          <div className="flex items-center gap-4">
            <Label className="font-semibold">当前分析模板:</Label>
            <Select
              value={selectedTemplateId || ''}
              onValueChange={(id) => setSelectedTemplateId(id)}
            >
              <SelectTrigger className="w-[280px]">
                <SelectValue placeholder="选择一个模板..." />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(localTemplateSets).map(([id, set]) => (
                  <SelectItem key={id} value={id}>{set.name} ({id})</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button variant="outline" onClick={() => setIsCreatingTemplate(true)} disabled={isCreatingTemplate}>+ 新建模板</Button>
            <Button variant="destructive" onClick={handleDeleteTemplate} disabled={!selectedTemplateId}>删除当前模板</Button>
          </div>

          {isCreatingTemplate && (
            <div className="space-y-3 p-3 border rounded-md border-dashed">
              <h4 className="font-semibold">新建分析模板集</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Input
                  placeholder="模板 ID (e.g., standard_v2)"
                  value={newTemplateId}
                  onChange={(e) => setNewTemplateId(e.target.value.replace(/\s/g, ''))}
                />
                <Input
                  placeholder="模板名称 (e.g., 标准分析模板V2)"
                  value={newTemplateName}
                  onChange={(e) => setNewTemplateName(e.target.value)}
                />
              </div>
              <div className="flex gap-2">
                <Button onClick={handleAddTemplate}>确认创建</Button>
                <Button variant="ghost" onClick={() => setIsCreatingTemplate(false)}>取消</Button>
              </div>
            </div>
          )}
        </div>

        <Separator />

        {/* --- Level 2: Module Management (within selected template) --- */}
        {selectedTemplateId && localTemplateSets[selectedTemplateId] ? (
          <div className="space-y-6">
            {Object.entries(localTemplateSets[selectedTemplateId].modules).map(([moduleId, config]) => {
              const allModulesInSet = localTemplateSets[selectedTemplateId].modules;

              return (
                <div key={moduleId} className="space-y-4 p-4 border rounded-lg">
                  <div className="flex justify-between items-start">
                    <div className="space-y-1">
                      <h3 className="text-lg font-semibold">{config.name || moduleId}</h3>
                      <p className="text-sm text-muted-foreground">ID: <Badge variant="secondary">{moduleId}</Badge></p>
                    </div>
                    <Button variant="destructive" size="sm" onClick={() => handleDeleteModule(moduleId)}>删除模块</Button>
                  </div>

                    <div className="space-y-2">
                    <Label>Model (Provider)</Label>
                    <ModelSelector
                      value={{ providerId: config.provider_id, modelId: config.model_id }}
                      onChange={(pId, mId) => {
                        handleAnalysisChange(moduleId, 'provider_id', pId);
                        handleAnalysisChange(moduleId, 'model_id', mId);
                      }}
                      allModels={allModels}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`${moduleId}-prompt`}>提示词模板</Label>
                    <Textarea
                      id={`${moduleId}-prompt`}
                      value={config.prompt_template || ''}
                      onChange={(e) => handleAnalysisChange(moduleId, 'prompt_template', e.target.value)}
                      rows={10}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>依赖模块 (Dependencies)</Label>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-2 p-2 border rounded-md">
                      {Object.keys(allModulesInSet)
                        .filter(id => id !== moduleId)
                        .map(depId => (
                          <div key={depId} className="flex items-center space-x-2">
                            <Checkbox
                              id={`${moduleId}-${depId}`}
                              checked={(config.dependencies || []).includes(depId)}
                              onCheckedChange={(checked) => updateAnalysisDependencies(moduleId, depId, !!checked)}
                            />
                            <label
                              htmlFor={`${moduleId}-${depId}`}
                              className="text-sm font-medium"
                            >
                              {allModulesInSet[depId]?.name || depId}
                            </label>
                          </div>
                        ))}
                    </div>
                  </div>
                </div>
              );
            })}

            {isCreatingModule && (
              <div className="space-y-4 p-4 border rounded-lg border-dashed">
                <h3 className="text-lg font-semibold">
                  在 &ldquo;{localTemplateSets[selectedTemplateId].name}&rdquo; 中新增分析模块
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="new-module-id">模块 ID (英文, 无空格)</Label>
                    <Input
                      id="new-module-id"
                      value={newModuleId}
                      onChange={(e) => setNewModuleId(e.target.value.replace(/\s/g, ''))}
                      placeholder="e.g. fundamental_analysis"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="new-module-name">模块名称</Label>
                    <Input
                      id="new-module-name"
                      value={newModuleName}
                      onChange={(e) => setNewModuleName(e.target.value)}
                      placeholder="e.g. 基本面分析"
                    />
                  </div>
                </div>
                <div className="flex gap-2">
                  <Button onClick={handleAddNewModule}>确认新增</Button>
                  <Button variant="ghost" onClick={() => setIsCreatingModule(false)}>取消</Button>
                </div>
              </div>
            )}

            <div className="flex items-center gap-4 pt-4 border-t">
              <Button onClick={() => setIsCreatingModule(true)} variant="outline" disabled={isCreatingModule}>
                + 新增分析模块
              </Button>
              <Button onClick={handleSaveAnalysis} disabled={isSavingAnalysis}>
                {isSavingAnalysis ? '保存中...' : '保存所有变更'}
              </Button>
              {analysisSaveMessage && (
                <span className={`text-sm ${analysisSaveMessage.includes('成功') ? 'text-green-600' : 'text-red-600'}`}>
                  {analysisSaveMessage}
                </span>
              )}
            </div>
          </div>
        ) : (
          <div className="text-center text-muted-foreground py-10">
            <p>请先选择或创建一个分析模板集。</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

