import { useCallback, useEffect, useMemo, useState } from 'react';
import { BookOpenText, ChevronLeft, ChevronRight, Loader2, Pencil, Plus, Search, Trash2, X } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/hooks/useAuth';
import { formatDate } from '@/lib/dateUtils';
import { isSupabaseConfigured } from '@/lib/supabase';
import {
  createProcurementDictionaryEntry,
  deleteProcurementDictionaryEntry,
  fetchProcurementDictionaryEntries,
  updateProcurementDictionaryEntry,
} from '@/services/modelOverrideService';
import type { ProcurementDictionaryEntry, ProcurementDictionaryTermType } from '@/types';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

interface ModelOverrideDictDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const TERM_TYPE_LABELS: Record<ProcurementDictionaryTermType, string> = {
  unique_model: '唯一型号',
  parameter: '参数',
  brand: '品牌',
  standard: '规范',
  general: '通用',
};

const TERM_TYPES = Object.keys(TERM_TYPE_LABELS) as ProcurementDictionaryTermType[];

export function ModelOverrideDictDialog({ open, onOpenChange }: ModelOverrideDictDialogProps) {
  const { user } = useAuth();
  const [entries, setEntries] = useState<ProcurementDictionaryEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [formDialogOpen, setFormDialogOpen] = useState(false);
  const [editingEntry, setEditingEntry] = useState<ProcurementDictionaryEntry | null>(null);
  const [formTerm, setFormTerm] = useState('');
  const [formTermType, setFormTermType] = useState<ProcurementDictionaryTermType>('parameter');
  const [formContext, setFormContext] = useState('');
  const [formInterpretation, setFormInterpretation] = useState('');
  const [formKeyword, setFormKeyword] = useState('');
  const [formEvidence, setFormEvidence] = useState('');
  const [formNote, setFormNote] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);

  const loadEntries = useCallback(async () => {
    if (!isSupabaseConfigured()) {
      setLoading(false);
      return;
    }
    try {
      setLoading(true);
      const data = await fetchProcurementDictionaryEntries();
      setEntries(data);
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      toast.error(`加载采购字典失败：${msg}`);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open) void loadEntries();
  }, [open, loadEntries]);

  useEffect(() => {
    if (!open) {
      setFormDialogOpen(false);
      setEditingEntry(null);
      setDeleteConfirmId(null);
      setSearchQuery('');
    }
  }, [open]);

  const filteredEntries = useMemo(() => {
    if (!searchQuery.trim()) return entries;

    return entries.filter(entry => {
        const q = searchQuery.trim().toLowerCase();
        return [
          entry.term,
          TERM_TYPE_LABELS[entry.term_type],
          entry.product_context,
          entry.interpretation,
          entry.suggested_keyword,
          entry.evidence,
          entry.note ?? '',
        ].some(value => value.toLowerCase().includes(q));
      });
  }, [entries, searchQuery]);

  const totalPages = Math.max(1, Math.ceil(filteredEntries.length / pageSize));
  const safePage = Math.min(page, totalPages);
  const pagedEntries = filteredEntries.slice((safePage - 1) * pageSize, safePage * pageSize);

  useEffect(() => {
    setPage(1);
  }, [searchQuery]);

  useEffect(() => {
    if (page > totalPages) {
      setPage(totalPages);
    }
  }, [page, totalPages]);

  function resetForm() {
    setFormTerm('');
    setFormTermType('parameter');
    setFormContext('');
    setFormInterpretation('');
    setFormKeyword('');
    setFormEvidence('');
    setFormNote('');
  }

  function openCreateDialog() {
    setEditingEntry(null);
    resetForm();
    setFormDialogOpen(true);
  }

  function openEditDialog(entry: ProcurementDictionaryEntry) {
    setEditingEntry(entry);
    setFormTerm(entry.term);
    setFormTermType(entry.term_type);
    setFormContext(entry.product_context);
    setFormInterpretation(entry.interpretation);
    setFormKeyword(entry.suggested_keyword);
    setFormEvidence(entry.evidence);
    setFormNote(entry.note ?? '');
    setFormDialogOpen(true);
  }

  async function handleSubmit() {
    if (!formTerm.trim() || !formInterpretation.trim()) {
      toast.error('术语和参数解读不能为空');
      return;
    }
    if (formTermType === 'unique_model' && !formKeyword.trim()) {
      toast.error('唯一型号条目需要填写推荐搜索词');
      return;
    }
    try {
      setSubmitting(true);
      if (editingEntry) {
        await updateProcurementDictionaryEntry(editingEntry.id, {
          term: formTerm,
          term_type: formTermType,
          product_context: formContext,
          interpretation: formInterpretation,
          suggested_keyword: formKeyword,
          evidence: formEvidence,
          note: formNote,
        });
        toast.success('采购字典条目已更新');
      } else {
        await createProcurementDictionaryEntry(
          {
            term: formTerm,
            term_type: formTermType,
            product_context: formContext,
            interpretation: formInterpretation,
            suggested_keyword: formKeyword,
            evidence: formEvidence,
            note: formNote,
          },
          user?.id,
        );
        toast.success('采购字典条目已添加');
      }
      setFormDialogOpen(false);
      await loadEntries();
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      toast.error(editingEntry ? `更新失败：${msg}` : `添加失败：${msg}`);
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(id: string) {
    try {
      await deleteProcurementDictionaryEntry(id);
      toast.success('采购字典条目已删除');
      setDeleteConfirmId(null);
      await loadEntries();
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      toast.error(`删除失败：${msg}`);
    }
  }

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-h-[85vh] overflow-hidden p-0 sm:max-w-6xl">
          <div className="flex h-full flex-col">
            <DialogHeader className="border-b px-6 py-4 text-left">
              <DialogTitle className="flex items-center gap-2">
                <BookOpenText className="h-5 w-5 text-blue-600" />
                采购字典管理
              </DialogTitle>
              <DialogDescription>
                管理标准化阶段沉淀的型号、参数、品牌、规范和采购语义解释。
              </DialogDescription>
            </DialogHeader>

            <div className="flex-1 overflow-y-auto px-6 py-5">
              {!isSupabaseConfigured() ? (
                <Card>
                  <CardContent className="py-12 text-center text-muted-foreground">
                    Supabase 未配置，无法使用采购字典。
                  </CardContent>
                </Card>
              ) : (
                <div className="space-y-4">
                  <div className="flex flex-wrap items-center justify-between gap-4">
                    <Button onClick={openCreateDialog}>
                      <Plus className="mr-1 h-4 w-4" /> 添加条目
                    </Button>
                    <div className="relative w-full sm:w-72">
                      <Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                      <Input
                        placeholder="搜索术语 / 解读 / 搜索词"
                        value={searchQuery}
                        onChange={e => setSearchQuery(e.target.value)}
                        className="pl-8 pr-8 text-sm"
                      />
                      {searchQuery && (
                        <button
                          onClick={() => setSearchQuery('')}
                          className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                        >
                          <X className="h-4 w-4" />
                        </button>
                      )}
                    </div>
                  </div>

                  <Card className="min-h-0">
                    <CardContent className="flex min-h-0 flex-col p-0">
                      {loading ? (
                        <div className="flex items-center justify-center py-12">
                          <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
                          <span className="ml-2 text-sm text-muted-foreground">加载中…</span>
                        </div>
                      ) : entries.length === 0 ? (
                        <div className="py-12 text-center text-muted-foreground">
                          <BookOpenText className="mx-auto mb-3 h-10 w-10 opacity-40" />
                          <p className="text-sm">暂无采购字典条目</p>
                        </div>
                      ) : filteredEntries.length === 0 ? (
                        <div className="py-12 text-center text-muted-foreground">
                          <Search className="mx-auto mb-3 h-10 w-10 opacity-40" />
                          <p className="text-sm">没有匹配「{searchQuery}」的条目</p>
                        </div>
                      ) : (
                        <>
                        <div className="max-h-[calc(85vh-260px)] overflow-auto">
                          <Table className="min-w-[980px]">
                            <TableHeader className="sticky top-0 z-10 bg-background">
                              <TableRow>
                                <TableHead>术语</TableHead>
                                <TableHead>类型</TableHead>
                                <TableHead>语境</TableHead>
                                <TableHead>参数解读</TableHead>
                                <TableHead>推荐搜索词</TableHead>
                                <TableHead>次数</TableHead>
                                <TableHead>更新时间</TableHead>
                                <TableHead className="text-right">操作</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {pagedEntries.map(entry => (
                                <TableRow key={entry.id}>
                                  <TableCell className="font-mono font-medium">{entry.term}</TableCell>
                                  <TableCell>
                                    <Badge variant={entry.term_type === 'unique_model' ? 'default' : 'secondary'}>
                                      {TERM_TYPE_LABELS[entry.term_type]}
                                    </Badge>
                                  </TableCell>
                                  <TableCell className="max-w-[160px] truncate text-muted-foreground">
                                    {entry.product_context || '-'}
                                  </TableCell>
                                  <TableCell className="max-w-[300px] truncate">{entry.interpretation}</TableCell>
                                  <TableCell className="max-w-[180px] truncate">{entry.suggested_keyword || '-'}</TableCell>
                                  <TableCell>{entry.occurrence_count}</TableCell>
                                  <TableCell className="text-muted-foreground">{formatDate(entry.updated_at)}</TableCell>
                                  <TableCell className="text-right">
                                    <div className="flex items-center justify-end gap-1">
                                      <Tooltip>
                                        <TooltipTrigger asChild>
                                          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEditDialog(entry)}>
                                            <Pencil className="h-4 w-4" />
                                          </Button>
                                        </TooltipTrigger>
                                        <TooltipContent>编辑</TooltipContent>
                                      </Tooltip>
                                      {deleteConfirmId === entry.id ? (
                                        <div className="flex items-center gap-1">
                                          <Button variant="destructive" size="sm" onClick={() => handleDelete(entry.id)}>确认删除</Button>
                                          <Button variant="ghost" size="sm" onClick={() => setDeleteConfirmId(null)}>取消</Button>
                                        </div>
                                      ) : (
                                        <Tooltip>
                                          <TooltipTrigger asChild>
                                            <Button
                                              variant="ghost"
                                              size="icon"
                                              className="h-8 w-8 text-destructive hover:text-destructive"
                                              onClick={() => setDeleteConfirmId(entry.id)}
                                            >
                                              <Trash2 className="h-4 w-4" />
                                            </Button>
                                          </TooltipTrigger>
                                          <TooltipContent>删除</TooltipContent>
                                        </Tooltip>
                                      )}
                                    </div>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                        <div className="flex flex-col gap-3 border-t px-4 py-3 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
                          <div className="flex items-center gap-2">
                            <span>每页</span>
                            <Select value={String(pageSize)} onValueChange={value => { setPageSize(Number(value)); setPage(1); }}>
                              <SelectTrigger className="h-8 w-[70px]">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="20">20</SelectItem>
                                <SelectItem value="50">50</SelectItem>
                                <SelectItem value="100">100</SelectItem>
                              </SelectContent>
                            </Select>
                            <span>条，共 {filteredEntries.length} 条</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Button
                              variant="outline"
                              size="icon"
                              className="h-8 w-8"
                              disabled={safePage <= 1}
                              onClick={() => setPage(safePage - 1)}
                              aria-label="上一页"
                            >
                              <ChevronLeft className="h-4 w-4" />
                            </Button>
                            <span className="px-2">{safePage} / {totalPages}</span>
                            <Button
                              variant="outline"
                              size="icon"
                              className="h-8 w-8"
                              disabled={safePage >= totalPages}
                              onClick={() => setPage(safePage + 1)}
                              aria-label="下一页"
                            >
                              <ChevronRight className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                        </>
                      )}
                    </CardContent>
                  </Card>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={formDialogOpen} onOpenChange={setFormDialogOpen}>
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <BookOpenText className="h-5 w-5 text-blue-600" />
              {editingEntry ? '编辑采购字典条目' : '添加采购字典条目'}
            </DialogTitle>
            <DialogDescription>
              唯一型号会继续用于命中后自动判定标准化成功并注入推荐搜索词。
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-2 sm:grid-cols-2">
            <div className="space-y-2">
              <Label>
                术语 <span className="text-destructive">*</span>
              </Label>
              <Input
                placeholder="如：2R、GEB371、DN100"
                value={formTerm}
                onChange={e => setFormTerm(e.target.value)}
                className="font-mono"
              />
            </div>
            <div className="space-y-2">
              <Label>类型</Label>
              <Select value={formTermType} onValueChange={(value) => setFormTermType(value as ProcurementDictionaryTermType)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {TERM_TYPES.map(type => (
                    <SelectItem key={type} value={type}>{TERM_TYPE_LABELS[type]}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>适用语境</Label>
              <Input
                placeholder="如：丁基防水胶带"
                value={formContext}
                onChange={e => setFormContext(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>推荐搜索词</Label>
              <Input
                placeholder="如：2R丁基防水胶带"
                value={formKeyword}
                onChange={e => setFormKeyword(e.target.value)}
              />
            </div>
            <div className="space-y-2 sm:col-span-2">
              <Label>
                参数解读 <span className="text-destructive">*</span>
              </Label>
              <Textarea
                placeholder="如：2R 在该防水胶带语境下表示双面防水/双面胶接类参数"
                value={formInterpretation}
                onChange={e => setFormInterpretation(e.target.value)}
                rows={3}
              />
            </div>
            <div className="space-y-2 sm:col-span-2">
              <Label>依据</Label>
              <Input
                placeholder="如：行业常用型号结构、原始规格、技术标准"
                value={formEvidence}
                onChange={e => setFormEvidence(e.target.value)}
              />
            </div>
            <div className="space-y-2 sm:col-span-2">
              <Label>备注</Label>
              <Input
                placeholder="可选备注"
                value={formNote}
                onChange={e => setFormNote(e.target.value)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setFormDialogOpen(false)} disabled={submitting}>
              取消
            </Button>
            <Button onClick={handleSubmit} disabled={submitting}>
              {submitting && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
              {editingEntry ? '保存' : '添加'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
