import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { SearchStageConfig } from './SearchStageConfig';
import { normalizeSearchPipelineConfig, type SearchPipelineConfig } from '@/types';
import { toast } from 'sonner';

const STORAGE_KEY = 'search-pipeline-config';

export function loadCachedPipelineConfig(): SearchPipelineConfig | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    return normalizeSearchPipelineConfig(JSON.parse(raw));
  } catch {
    return null;
  }
}

function savePipelineConfig(config: SearchPipelineConfig) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(normalizeSearchPipelineConfig(config)));
}

interface SearchConfigDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  value: SearchPipelineConfig;
  onChange: (config: SearchPipelineConfig) => void;
}

export function SearchConfigDialog({
  open,
  onOpenChange,
  value,
  onChange,
}: SearchConfigDialogProps) {
  const [draft, setDraft] = useState<SearchPipelineConfig>(() => normalizeSearchPipelineConfig(value));

  useEffect(() => {
    if (open) setDraft(normalizeSearchPipelineConfig(value));
  }, [open, value]);

  const handleConfirm = () => {
    const normalized = normalizeSearchPipelineConfig(draft);
    onChange(normalized);
    savePipelineConfig(normalized);
    toast.success('搜索配置已保存');
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      {/* [&>button:last-child]:hidden 隐藏 DialogContent 内置的 ✕ 关闭按钮 */}
      <DialogContent className="sm:max-w-4xl max-h-[85vh] overflow-y-auto [&>button:last-child]:hidden">
        {/* 自定义头部：标题在左，取消/确定在右 */}
        <div className="flex items-start justify-between gap-4 pr-2">
          <div>
            <DialogTitle className="text-lg font-semibold">搜索配置</DialogTitle>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <Button variant="outline" size="sm" onClick={() => onOpenChange(false)}>取消</Button>
            <Button size="sm" onClick={handleConfirm}>确定</Button>
          </div>
        </div>
        <div className="py-2">
          <SearchStageConfig value={draft} onChange={setDraft} />
        </div>
      </DialogContent>
    </Dialog>
  );
}
