import { useState, useEffect, useCallback } from 'react';
import { Switch } from '@/components/ui/switch';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, Save } from 'lucide-react';
import {
  type SearchPipelineConfig,
  type SearchFieldType,
  type SearchPreset,
  DEFAULT_SEARCH_PIPELINE_CONFIG,
  SEARCH_FIELD_ORDER,
  SEARCH_FIELD_LABELS,
  BUILTIN_SEARCH_TEMPLATES,
  createDefaultKeywordCombination,
  normalizeKeywordCombinationFields,
  normalizeSearchPipelineConfig,
  normalizeSearchPreset,
  buildKeywordCombinationLabel,
} from '@/types';
import { resolveSearchTemplateId, shouldShowAdvancedSearchTemplate } from '@/lib/searchTemplateResolution';
import { useAuth } from '@/hooks/useAuth';
import { fetchSearchPresets, createSearchPreset, deleteSearchPreset } from '@/services/searchPresetService';
import { toast } from 'sonner';

interface SearchStageConfigProps {
  value: SearchPipelineConfig;
  onChange: (config: SearchPipelineConfig) => void;
}

export function SearchStageConfig({ value, onChange }: SearchStageConfigProps) {
  const { user } = useAuth();
  const [presets, setPresets] = useState<SearchPreset[]>([]);
  const [selectedTemplateId, setSelectedTemplateId] = useState(() => resolveSearchTemplateId(value, []));
  const [showAdvanced, setShowAdvanced] = useState(() => shouldShowAdvancedSearchTemplate(resolveSearchTemplateId(value, []), []));
  const [presetName, setPresetName] = useState('');
  const [savingPreset, setSavingPreset] = useState(false);

  // 加载用户预设
  useEffect(() => {
    if (user?.id) {
      fetchSearchPresets(user.id)
        .then(items => setPresets(items.map(normalizeSearchPreset)))
        .catch(() => {});
    }
  }, [user?.id]);

  useEffect(() => {
    const nextTemplateId = resolveSearchTemplateId(value, presets, selectedTemplateId);
    if (nextTemplateId !== selectedTemplateId) {
      setSelectedTemplateId(nextTemplateId);
    }

    const nextShowAdvanced = shouldShowAdvancedSearchTemplate(nextTemplateId, presets);
    if (nextShowAdvanced !== showAdvanced) {
      setShowAdvanced(nextShowAdvanced);
    }
  }, [presets, selectedTemplateId, showAdvanced, value]);

  const handleTemplateChange = useCallback((templateId: string) => {
    setSelectedTemplateId(templateId);

    // 内置模板
    const builtin = BUILTIN_SEARCH_TEMPLATES.find(t => t.id === templateId);
    if (builtin) {
      onChange(normalizeSearchPipelineConfig(builtin.config));
      setShowAdvanced(false);
      return;
    }

    // 用户预设
    const preset = presets.find(p => p.id === templateId);
    if (preset) {
      onChange(normalizeSearchPipelineConfig(preset.config));
      setShowAdvanced(preset.config.keywordCombinations.length > 0);
      return;
    }

    // 自定义
    if (templateId === 'custom') {
      setShowAdvanced(true);
      // 如果当前没有自定义组合，初始化一个空组合
      if (value.keywordCombinations.length === 0) {
        onChange({
          ...value,
          keywordCombinations: [createDefaultKeywordCombination()],
        });
      }
    }
  }, [onChange, presets, value]);

  const updateField = useCallback(<K extends keyof SearchPipelineConfig>(
    key: K,
    val: SearchPipelineConfig[K],
  ) => {
    onChange({ ...value, [key]: val });
  }, [onChange, value]);

  const addCombination = useCallback(() => {
    onChange({
      ...value,
      keywordCombinations: [
        ...value.keywordCombinations,
        createDefaultKeywordCombination(),
      ],
    });
  }, [onChange, value]);

  const removeCombination = useCallback((index: number) => {
    const next = value.keywordCombinations.filter((_, i) => i !== index);
    onChange({ ...value, keywordCombinations: next });
  }, [onChange, value]);

  const toggleFieldInCombination = useCallback((comboIndex: number, field: SearchFieldType) => {
    const combos = [...value.keywordCombinations];
    const combo = combos[comboIndex];
    if (!combo) return;

    const fields = normalizeKeywordCombinationFields(combo.fields.includes(field)
      ? combo.fields.filter(f => f !== field)
      : [...combo.fields, field]);

    // 至少保留一个字段
    if (fields.length === 0) return;

    const label = buildKeywordCombinationLabel(fields);
    combos[comboIndex] = { fields, label };
    onChange({ ...value, keywordCombinations: combos });
  }, [onChange, value]);

  const handleSavePreset = useCallback(async () => {
    if (!user?.id || !presetName.trim()) {
      toast.error('请输入预设名称');
      return;
    }
    setSavingPreset(true);
    try {
      const preset = await createSearchPreset({
        user_id: user.id,
        name: presetName.trim(),
        config: normalizeSearchPipelineConfig(value),
      });
      setPresets(prev => [normalizeSearchPreset(preset), ...prev]);
      setPresetName('');
      toast.success('预设已保存');
    } catch (err) {
      toast.error(`保存失败: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setSavingPreset(false);
    }
  }, [user?.id, presetName, value]);

  const handleDeletePreset = useCallback(async (presetId: string) => {
    try {
      await deleteSearchPreset(presetId);
      setPresets(prev => prev.filter(p => p.id !== presetId));
      if (selectedTemplateId === presetId) {
        setSelectedTemplateId('default');
        onChange({ ...DEFAULT_SEARCH_PIPELINE_CONFIG });
      }
      toast.success('预设已删除');
    } catch (err) {
      toast.error(`删除失败: ${err instanceof Error ? err.message : String(err)}`);
    }
  }, [selectedTemplateId, onChange]);

  const configSummary = (() => {
    const stages: string[] = [];
    if (value.keywordSearchEnabled) {
      if (value.keywordCombinations.length > 0) {
        stages.push(`关键词搜索（${value.keywordCombinations.map(c => c.label).join('、')}）`);
      } else {
        stages.push(
          value.includeAiKeyword
            ? '关键词搜索（默认递减，含主搜索词优先轮次）'
            : '关键词搜索（默认递减）',
        );
      }
    }
    if (value.imageSearchEnabled) stages.push('图搜');
    return stages.join(' → ');
  })();

  return (
    <div className="space-y-4">
      {/* 横向两栏布局 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 左栏：阶段开关 + 搜索规则模板 */}
        <div className="space-y-4">
          <div className="space-y-2">
            <label className="text-sm font-semibold">搜索阶段</label>
            <div className="flex items-center justify-between rounded-md border p-3">
              <span className="text-sm">关键词组合搜索</span>
              <Switch
                checked={value.keywordSearchEnabled}
                onCheckedChange={v => updateField('keywordSearchEnabled', v)}
              />
            </div>
            <div className="flex items-center justify-between rounded-md border p-3">
              <span className="text-sm">图搜</span>
              <Switch
                checked={value.imageSearchEnabled}
                onCheckedChange={v => updateField('imageSearchEnabled', v)}
              />
            </div>
          </div>

          {value.keywordSearchEnabled && (
            <div className="space-y-3">
              <div className="space-y-2">
                <label className="text-sm font-semibold">搜索规则模板</label>
                <Select value={selectedTemplateId} onValueChange={handleTemplateChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择搜索模板" />
                  </SelectTrigger>
                  <SelectContent>
                    {BUILTIN_SEARCH_TEMPLATES.map(t => (
                      <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
                    ))}
                    <SelectItem value="custom">自定义组合...</SelectItem>
                    {presets.length > 0 && (
                      <>
                        <div className="px-2 py-1.5 text-xs text-muted-foreground font-medium border-t mt-1 pt-1.5">
                          已保存的预设
                        </div>
                        {presets.map(p => (
                          <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                        ))}
                      </>
                    )}
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-center justify-between rounded-md border p-3">
                <div>
                  <span className="text-sm">主搜索词优先轮次（仅默认递减策略生效）</span>
                </div>
                <Switch
                  checked={value.includeAiKeyword}
                  onCheckedChange={v => updateField('includeAiKeyword', v)}
                />
              </div>

              {/* 预设管理 */}
              <div className="space-y-2 rounded-md border p-3">
                <label className="text-sm font-semibold">保存/加载预设</label>
                <div className="flex items-center gap-2">
                  <Input
                    placeholder="预设名称"
                    value={presetName}
                    onChange={e => setPresetName(e.target.value)}
                    className="flex-1 h-8 text-sm"
                  />
                  <Button
                    variant="destructive"
                    size="sm"
                    onClick={handleSavePreset}
                    disabled={savingPreset || !presetName.trim()}
                  >
                    <Save className="h-3.5 w-3.5 mr-1" />
                    保存
                  </Button>
                </div>
                {presets.length > 0 && (
                  <div className="space-y-1 pt-1">
                    {presets.map(p => (
                      <div key={p.id} className="flex items-center justify-between text-sm rounded border px-2.5 py-1.5">
                        <button
                          type="button"
                          className="text-left hover:underline truncate flex-1"
                          onClick={() => handleTemplateChange(p.id)}
                        >
                          {p.name}
                        </button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-6 w-6 shrink-0 text-muted-foreground hover:text-destructive"
                          onClick={() => handleDeletePreset(p.id)}
                        >
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* 右栏：自定义关键词组合轮次 */}
        {value.keywordSearchEnabled && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <label className="text-sm font-semibold">搜索轮次配置</label>
              {(selectedTemplateId === 'custom' || showAdvanced) && (
                <Button variant="outline" size="sm" onClick={addCombination}>
                  <Plus className="h-3.5 w-3.5 mr-1" />添加轮次
                </Button>
              )}
            </div>

            {value.keywordCombinations.length === 0 ? (
              <div className="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground">
                当前使用默认递减策略，会从主搜索词逐步删减字段。
                <br />
                <span className="text-xs">选择「自定义组合」模板可手动配置搜索轮次。</span>
              </div>
            ) : (
              <div className="space-y-2">
                {value.keywordCombinations.map((combo, comboIndex) => (
                  <div key={comboIndex} className="flex items-start gap-2 rounded-md border p-3">
                    <div className="flex-1 space-y-2">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium">轮次 {comboIndex + 1}</span>
                        <Badge variant="secondary" className="text-xs">{combo.label}</Badge>
                      </div>
                      <div className="flex flex-wrap gap-x-4 gap-y-1.5">
                        {SEARCH_FIELD_ORDER.map(field => (
                          <label key={field} className="flex items-center gap-1.5 text-sm cursor-pointer">
                            <Checkbox
                              checked={combo.fields.includes(field)}
                              onCheckedChange={() => toggleFieldInCombination(comboIndex, field)}
                            />
                            {SEARCH_FIELD_LABELS[field]}
                          </label>
                        ))}
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
                      onClick={() => removeCombination(comboIndex)}
                      disabled={value.keywordCombinations.length <= 1}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* 配置摘要 */}
      {configSummary && (
        <div className="rounded-md bg-muted/50 px-4 py-2.5 text-sm">
          <span className="text-muted-foreground">执行方式：</span>{configSummary}
        </div>
      )}
    </div>
  );
}
