import { useCallback, useEffect, useState } from 'react';
import { BookOpenText, 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 {
  createModelOverride,
  deleteModelOverride,
  fetchModelOverrides,
  updateModelOverride,
} from '@/services/modelOverrideService';
import type { ModelOverride } from '@/types';
import { Button } from '@/components/ui/button';
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

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

export function ModelOverrideDictDialog({ open, onOpenChange }: ModelOverrideDictDialogProps) {
  const { user } = useAuth();
  const [entries, setEntries] = useState<ModelOverride[]>([]);
  const [loading, setLoading] = useState(false);
  const [formDialogOpen, setFormDialogOpen] = useState(false);
  const [editingEntry, setEditingEntry] = useState<ModelOverride | null>(null);
  const [formModelNumber, setFormModelNumber] = useState('');
  const [formKeyword, setFormKeyword] = useState('');
  const [formNote, setFormNote] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');

  const loadEntries = useCallback(async () => {
    if (!isSupabaseConfigured()) {
      setLoading(false);
      return;
    }
    try {
      setLoading(true);
      const data = await fetchModelOverrides();
      setEntries(data);
    } catch {
      toast.error('加载字典失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

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

  const filteredEntries = searchQuery.trim()
    ? entries.filter(e => {
        const q = searchQuery.trim().toLowerCase();
        return (
          e.model_number.toLowerCase().includes(q) ||
          e.suggested_keyword.toLowerCase().includes(q) ||
          (e.note ?? '').toLowerCase().includes(q)
        );
      })
    : entries;

  function openCreateDialog() {
    setEditingEntry(null);
    setFormModelNumber('');
    setFormKeyword('');
    setFormNote('');
    setFormDialogOpen(true);
  }

  function openEditDialog(entry: ModelOverride) {
    setEditingEntry(entry);
    setFormModelNumber(entry.model_number);
    setFormKeyword(entry.suggested_keyword);
    setFormNote(entry.note ?? '');
    setFormDialogOpen(true);
  }

  async function handleSubmit() {
    if (!formModelNumber.trim() || !formKeyword.trim()) {
      toast.error('型号和推荐搜索词不能为空');
      return;
    }
    try {
      setSubmitting(true);
      if (editingEntry) {
        await updateModelOverride(editingEntry.id, {
          model_number: formModelNumber.trim(),
          suggested_keyword: formKeyword.trim(),
          note: formNote.trim() || undefined,
        });
        toast.success('字典条目已更新');
      } else {
        await createModelOverride(
          {
            model_number: formModelNumber.trim(),
            suggested_keyword: formKeyword.trim(),
            note: formNote.trim() || undefined,
          },
          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 deleteModelOverride(id);
      toast.success('字典条目已删除');
      setDeleteConfirmId(null);
      await loadEntries();
    } catch {
      toast.error('删除失败');
    }
  }

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-h-[85vh] overflow-hidden p-0 sm:max-w-4xl">
          <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 items-center justify-between gap-4">
                    <Button onClick={openCreateDialog}>
                      <Plus className="mr-1 h-4 w-4" /> 添加条目
                    </Button>
                    <div className="relative w-56">
                      <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>
                    <CardContent className="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="overflow-x-auto">
                          <Table className="min-w-[680px]">
                            <TableHeader>
                              <TableRow>
                                <TableHead>型号</TableHead>
                                <TableHead>推荐搜索词</TableHead>
                                <TableHead>备注</TableHead>
                                <TableHead>创建时间</TableHead>
                                <TableHead className="text-right">操作</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {filteredEntries.map(entry => (
                                <TableRow key={entry.id}>
                                  <TableCell className="font-mono font-medium">{entry.model_number}</TableCell>
                                  <TableCell>{entry.suggested_keyword}</TableCell>
                                  <TableCell className="text-muted-foreground">{entry.note || '—'}</TableCell>
                                  <TableCell className="text-muted-foreground">{formatDate(entry.created_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>
                      )}
                    </CardContent>
                  </Card>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 新增 / 编辑表单 Dialog */}
      <Dialog open={formDialogOpen} onOpenChange={setFormDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <BookOpenText className="h-5 w-5 text-blue-600" />
              {editingEntry ? '编辑字典条目' : '添加字典条目'}
            </DialogTitle>
            <DialogDescription>
              型号使用大小写不敏感匹配，推荐搜索词会直接注入到标准化结果中。
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label>
                型号 <span className="text-destructive">*</span>
              </Label>
              <Input
                placeholder="如：GEB371"
                value={formModelNumber}
                onChange={e => setFormModelNumber(e.target.value)}
                className="font-mono"
              />
            </div>
            <div className="space-y-2">
              <Label>
                推荐搜索词 <span className="text-destructive">*</span>
              </Label>
              <Input
                placeholder="如：GEB371外挂电池"
                value={formKeyword}
                onChange={e => setFormKeyword(e.target.value)}
              />
            </div>
            <div className="space-y-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>
    </>
  );
}
