"use client";

import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import type { LucideIcon } from "lucide-react";
import { Pencil, Plus, Search, Trash2, Eye } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog as EnhancedDialog,
  DialogBody,
  DialogContent as EnhancedDialogContent,
  DialogFooter as EnhancedDialogFooter,
} from "@/components/common/shadcn-enhanced";
import { DateTimePicker } from "@/components/common/shadcn-enhanced/date-time-picker";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";

function parseYearValue(value: unknown): Date | null {
  if (value === null || value === undefined || value === "") {
    return null;
  }
  const year = Number(value);
  if (Number.isNaN(year)) {
    return null;
  }
  return new Date(year, 0, 1);
}

function formatYearValue(date: Date | null): string {
  if (!date) {
    return "";
  }
  return String(date.getFullYear());
}

function parseDateValue(value: unknown): Date | null {
  if (value === null || value === undefined || value === "") {
    return null;
  }

  if (value instanceof Date && !Number.isNaN(value.getTime())) {
    return value;
  }

  const text = String(value).trim();
  const datePart = text.slice(0, 10);
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(datePart);
  if (match) {
    const year = Number(match[1]);
    const month = Number(match[2]) - 1;
    const day = Number(match[3]);
    const date = new Date(year, month, day);
    if (
      date.getFullYear() === year &&
      date.getMonth() === month &&
      date.getDate() === day
    ) {
      return date;
    }
  }

  const parsed = new Date(text);
  return Number.isNaN(parsed.getTime()) ? null : parsed;
}

function formatDateValue(date: Date | null): string {
  if (!date) {
    return "";
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function YearFormField({
  fieldKey,
  value,
  onFieldChange,
  placeholder,
  required,
}: {
  fieldKey: string;
  value: unknown;
  onFieldChange: (key: string, value: string) => void;
  placeholder?: string;
  required?: boolean;
}) {
  const yearValue = useMemo(() => parseYearValue(value), [value]);
  const handleChange = useCallback(
    (date: Date | null) => onFieldChange(fieldKey, formatYearValue(date)),
    [fieldKey, onFieldChange],
  );

  return (
    <DateTimePicker
      id={fieldKey}
      mode="year"
      value={yearValue}
      onChange={handleChange}
      placeholder={placeholder ?? "请选择年份"}
      clearable={!required}
      required={required}
      className="w-full"
    />
  );
}

function DateFormField({
  fieldKey,
  value,
  onFieldChange,
  placeholder,
  required,
}: {
  fieldKey: string;
  value: unknown;
  onFieldChange: (key: string, value: string) => void;
  placeholder?: string;
  required?: boolean;
}) {
  const dateValue = useMemo(() => parseDateValue(value), [value]);
  const handleChange = useCallback(
    (date: Date | null) => onFieldChange(fieldKey, formatDateValue(date)),
    [fieldKey, onFieldChange],
  );

  return (
    <DateTimePicker
      id={fieldKey}
      mode="date"
      value={dateValue}
      onChange={handleChange}
      placeholder={placeholder ?? "请选择日期"}
      clearable={!required}
      required={required}
      showToday
      className="w-full"
    />
  );
}

export interface BrapiTableColumn {
  key: string;
  label: string;
  render?: (value: unknown, row: Record<string, unknown>) => React.ReactNode;
}

export interface BrapiFormField {
  key: string;
  label: string;
  type: "text" | "select" | "date" | "number" | "textarea" | "year";
  required?: boolean;
  /** 只读展示，用户不可编辑（如后端自动生成的字段） */
  readOnly?: boolean;
  placeholder?: string;
  options?: Array<{ value: string; label: string }>;
  colSpan?: 1 | 2;
}

export interface BrapiStatBadge {
  label: string;
  value: number | string;
  className: string;
}

interface BrapiEntityPageProps {
  icon: LucideIcon;
  iconBg: string;
  title: string;
  description: string;
  addLabel?: string;
  columns: BrapiTableColumn[];
  fields: BrapiFormField[];
  data: Record<string, unknown>[];
  stats?: BrapiStatBadge[];
  loadData?: () => Promise<Record<string, unknown>[]>;
  fetchRecord?: (id: string) => Promise<Record<string, unknown>>;
  createRecord?: (payload: Record<string, unknown>) => Promise<Record<string, unknown>>;
  updateRecord?: (id: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>;
  deleteRecord?: (id: string) => Promise<void>;
  renderQueryForm?: (props: { keyword: string; onKeywordChange: (value: string) => void }) => ReactNode;
  renderFormExtra?: (props: {
    formData: Record<string, unknown>;
    updateForm: (key: string, value: string) => void;
    updateFormBatch: (patch: Record<string, unknown>) => void;
    editingRow: Record<string, unknown> | null;
  }) => ReactNode;
  /** 使用 common/shadcn-enhanced 公用 Dialog（可拖拽、最大化） */
  useEnhancedDialog?: boolean;
  /** 新增弹窗默认表单值（如从详情页预填 plate_id） */
  defaultFormValues?: Record<string, unknown>;
}

export function BrapiEntityPage({
  icon: Icon,
  iconBg,
  title,
  description,
  addLabel = "新增记录",
  columns,
  fields,
  data: initialData,
  stats,
  loadData,
  fetchRecord,
  createRecord,
  updateRecord,
  deleteRecord,
  renderQueryForm,
  renderFormExtra,
  useEnhancedDialog = false,
  defaultFormValues,
}: BrapiEntityPageProps) {
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(Boolean(loadData));
  const [error, setError] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [editingRow, setEditingRow] = useState<Record<string, unknown> | null>(null);
  const [formData, setFormData] = useState<Record<string, unknown>>({});
  const [search, setSearch] = useState("");
  const [deletingRow, setDeletingRow] = useState<Record<string, unknown> | null>(null);
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [recordLoadingId, setRecordLoadingId] = useState<string | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailRow, setDetailRow] = useState<Record<string, unknown> | null>(null);

  const resolveRowId = useCallback((row: Record<string, unknown>) => String(
    row.id
    ?? row.listDbId
    ?? row.ontologyDbId
    ?? row.locationDbId
    ?? row.personDbId
    ?? row.seasonDbId
    ?? row.programDbId
    ?? row.trialDbId
    ?? row.studyDbId
    ?? row.germplasmDbId
    ?? row.breedingMethodDbId
    ??     row.attributeDbId
    ?? row.attributeValueDbId
    ?? row.crossingProjectDbId
    ?? row.plannedCrossDbId
    ?? row.crossDbId
    ?? row.plateDbId
    ?? row.sampleDbId
    ?? row.referenceSetDbId
    ?? row.referenceDbId
    ?? row.referenceBasesDbId
    ?? row.variantSetDbId
    ?? row.callSetDbId
    ?? row.variantDbId
    ?? row.callDbId
    ?? row.mapDbId
    ?? row.linkageGroupDbId
    ?? row.markerPositionDbId
    ?? row.analysisDbId
    ?? row.formatDbId
    ?? "",
  ), []);

  const resolveRecord = useCallback(async (row: Record<string, unknown>) => {
    const id = resolveRowId(row);
    if (!fetchRecord || !id) {
      return row;
    }
    return fetchRecord(id);
  }, [fetchRecord, resolveRowId]);

  useEffect(() => {
    if (!loadData) return;
    let mounted = true;
    setLoading(true);
    setError(null);
    loadData()
      .then((rows) => { if (mounted) setData(rows); })
      .catch((event) => { if (mounted) setError(event instanceof Error ? event.message : "数据加载失败"); })
      .finally(() => { if (mounted) setLoading(false); });
    return () => { mounted = false; };
  }, [loadData]);

  const filteredData = useMemo(() => {
    const keyword = search.toLowerCase().trim();
    if (!keyword) return data;
    return data.filter((row) => columns.some((column) => String(row[column.key] ?? "").toLowerCase().includes(keyword)));
  }, [columns, data, search]);

  const totalPages = useMemo(() => Math.max(1, Math.ceil(filteredData.length / pageSize)), [filteredData.length, pageSize]);
  const pagedData = useMemo(() => {
    const start = (page - 1) * pageSize;
    return filteredData.slice(start, start + pageSize);
  }, [filteredData, page, pageSize]);

  useEffect(() => {
    setPage(1);
  }, [search, pageSize, data.length]);

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

  const openAdd = () => {
    setEditingRow(null);
    setFormData({
      ...fields.reduce<Record<string, unknown>>((defaults, field) => {
        if (field.type === "year") {
          defaults[field.key] = String(new Date().getFullYear());
        }
        return defaults;
      }, {}),
      ...(defaultFormValues ?? {}),
    });
    setOpen(true);
  };

  const openEdit = async (row: Record<string, unknown>) => {
    const id = resolveRowId(row);
    if (fetchRecord && id) {
      setRecordLoadingId(id);
    }
    try {
      const detail = await resolveRecord(row);
      setEditingRow(detail);
      setFormData({ ...detail });
      setOpen(true);
      setError(null);
    } catch (event) {
      setError(event instanceof Error ? event.message : "加载详情失败");
    } finally {
      setRecordLoadingId(null);
    }
  };

  const openView = async (row: Record<string, unknown>) => {
    const id = resolveRowId(row);
    if (fetchRecord && id) {
      setRecordLoadingId(id);
    }
    try {
      const detail = await resolveRecord(row);
      setDetailRow(detail);
      setDetailOpen(true);
      setError(null);
    } catch (event) {
      setError(event instanceof Error ? event.message : "加载详情失败");
    } finally {
      setRecordLoadingId(null);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      if (editingRow) {
        const rowId = resolveRowId(editingRow);
        if (updateRecord) {
          const updated = await updateRecord(rowId, formData);
          if (loadData) {
            const rows = await loadData();
            setData(rows);
          } else {
            setData((current) => current.map((row) => (resolveRowId(row) === rowId ? updated : row)));
          }
        } else if (loadData) {
          const rows = await loadData();
          setData(rows);
        } else {
          setData((current) => current.map((row) => (resolveRowId(row) === rowId ? { ...row, ...formData } : row)));
        }
      } else if (createRecord) {
        const created = await createRecord(formData);
        if (loadData) {
          const rows = await loadData();
          setData(rows);
        } else {
          setData((current) => [created, ...current]);
        }
      } else if (loadData) {
        const rows = await loadData();
        setData(rows);
      } else {
        setData((current) => [{ id: `${Date.now()}`, ...formData }, ...current]);
      }
      setOpen(false);
      setError(null);
    } catch (event) {
      setError(event instanceof Error ? event.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  const confirmDelete = (row: Record<string, unknown>) => setDeletingRow(row);

  const handleDelete = async () => {
    if (!deletingRow) return;
    const id = resolveRowId(deletingRow);
    setDeleting(true);
    try {
      if (deleteRecord) {
        await deleteRecord(id);
      }
      if (loadData) {
        const rows = await loadData();
        setData(rows);
      } else {
        setData((current) => current.filter((row) => resolveRowId(row) !== id));
      }
      setDeletingRow(null);
      setError(null);
    } catch (event) {
      setError(event instanceof Error ? event.message : "删除失败");
    } finally {
      setDeleting(false);
    }
  };

  const updateForm = useCallback((key: string, value: string) => {
    setFormData((current) => ({ ...current, [key]: value }));
  }, []);

  const updateFormBatch = useCallback((patch: Record<string, unknown>) => {
    setFormData((current) => ({ ...current, ...patch }));
  }, []);

  const formDialogTitle = editingRow ? `编辑 ${title}` : `新增 ${title}`;
  const deletingLabel = String(
    deletingRow?.name
    ?? deletingRow?.sample_name
    ?? deletingRow?.plate_name
    ?? deletingRow?.ontology_name
    ?? deletingRow?.ontologyName
    ?? deletingRow?.crop_name
    ?? deletingRow?.id
    ?? "该记录",
  );

  const formFieldsGrid = (
    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
      {renderFormExtra?.({ formData, updateForm, updateFormBatch, editingRow })}
      {fields.map((field) => (
        <div key={field.key} className={field.colSpan === 2 || field.type === "textarea" ? "md:col-span-2" : ""}>
          <Label htmlFor={field.key} className="mb-1.5 block text-sm text-slate-700 dark:text-slate-200">
            {field.label}{field.required ? <span className="ml-0.5 text-red-500">*</span> : null}
          </Label>
          {field.type === "year" ? (
            <YearFormField
              fieldKey={field.key}
              value={formData[field.key]}
              onFieldChange={updateForm}
              placeholder={field.placeholder}
              required={field.required}
            />
          ) : field.type === "date" ? (
            <DateFormField
              fieldKey={field.key}
              value={formData[field.key]}
              onFieldChange={updateForm}
              placeholder={field.placeholder}
              required={field.required}
            />
          ) : field.type === "select" ? (
            <Select
              value={String(formData[field.key] ?? "")}
              onValueChange={(value) => updateForm(field.key, value)}
              disabled={field.readOnly}
            >
              <SelectTrigger id={field.key}><SelectValue placeholder={field.placeholder ?? `请选择${field.label}`} /></SelectTrigger>
              <SelectContent
                position="popper"
                className={useEnhancedDialog ? "z-[110] max-h-60" : undefined}
              >
                {(field.options ?? []).map((option) => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
              </SelectContent>
            </Select>
          ) : field.type === "textarea" ? (
            <Textarea
              id={field.key}
              value={String(formData[field.key] ?? "")}
              onChange={(event) => updateForm(field.key, event.target.value)}
              placeholder={field.placeholder}
              rows={3}
              className="resize-none"
              readOnly={field.readOnly}
              disabled={field.readOnly}
            />
          ) : (
            <Input
              id={field.key}
              type={field.type === "number" ? "number" : "text"}
              value={String(formData[field.key] ?? "")}
              onChange={(event) => updateForm(field.key, event.target.value)}
              placeholder={field.placeholder}
              readOnly={field.readOnly}
              disabled={field.readOnly}
              className={field.readOnly ? "bg-slate-50 text-slate-500 dark:bg-slate-900 dark:text-slate-400" : undefined}
            />
          )}
        </div>
      ))}
    </div>
  );

  const formDialogFooter = (
    <>
      <Button variant="outline" onClick={() => setOpen(false)}>取消</Button>
      <Button onClick={handleSave} disabled={saving}>{saving ? "保存中..." : "保存"}</Button>
    </>
  );

  const deleteDialogFooter = (
    <>
      <Button variant="outline" onClick={() => setDeletingRow(null)} disabled={deleting}>取消</Button>
      <Button variant="destructive" onClick={handleDelete} disabled={deleting}>{deleting ? "删除中..." : "确认删除"}</Button>
    </>
  );

  const deleteDialogDescription = (
    <>
      删除后不可恢复。确认删除
      {" "}
      <span className="font-medium text-slate-700 dark:text-slate-200">{deletingLabel}</span>
      {" "}
      吗？
    </>
  );

  return (
    <div className="flex min-h-full flex-col">
      <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-center gap-3">
          <div className={cn("rounded-xl p-2.5", iconBg)}><Icon className="h-5 w-5 text-white" /></div>
          <div>
            <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-50">{title}</h2>
            <p className="mt-0.5 text-sm text-slate-500 dark:text-slate-400">{description}</p>
          </div>
        </div>
        {createRecord ? (
          <Button onClick={openAdd} className="shrink-0 gap-2"><Plus className="h-4 w-4" />{addLabel}</Button>
        ) : null}
      </div>

      {stats ? (
        <div className="mb-4 flex flex-wrap gap-2">
          {stats.map((stat) => <span key={stat.label} className={cn("rounded-full px-3 py-1 text-xs", stat.className)}>{stat.value} {stat.label}</span>)}
        </div>
      ) : null}

      {renderQueryForm ? (
        <div className="mb-4">
          {renderQueryForm({
            keyword: search,
            onKeywordChange: (value) => setSearch(value),
          })}
        </div>
      ) : (
        <div className="relative mb-4">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <Input placeholder="搜索..." value={search} onChange={(event) => setSearch(event.target.value)} className="bg-white pl-9 dark:bg-slate-950" />
        </div>
      )}

      {error ? <div className="mb-4 rounded-xl border border-destructive/20 bg-destructive/10 px-4 py-3 text-sm font-medium text-destructive">{error}</div> : null}

      <div className="min-h-0 flex-1 overflow-hidden rounded-xl border border-slate-200 bg-white transition-colors duration-300 ease-out dark:border-slate-800 dark:bg-slate-950">
        <Table>
          <TableHeader>
            <TableRow className="border-slate-200 bg-slate-50 transition-colors duration-300 ease-out dark:border-slate-800 dark:bg-slate-900">
              <TableHead className="w-10 text-xs font-medium text-slate-400 transition-colors duration-300 ease-out dark:text-slate-500">#</TableHead>
              {columns.map((column) => <TableHead key={column.key} className="text-xs font-medium text-slate-500 transition-colors duration-300 ease-out dark:text-slate-300">{column.label}</TableHead>)}
              <TableHead className="w-24 pr-4 text-right text-xs font-medium text-slate-500 transition-colors duration-300 ease-out dark:text-slate-300">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              Array.from({ length: Math.min(pageSize, 8) }).map((_, rowIndex) => (
                <TableRow key={`loading-${rowIndex}`} className="border-slate-100 dark:border-slate-800">
                  <TableCell><Skeleton className="h-4 w-5" /></TableCell>
                  {columns.map((column, columnIndex) => (
                    <TableCell key={column.key}>
                      <Skeleton className={cn("h-4", columnIndex % 3 === 0 ? "w-28" : columnIndex % 3 === 1 ? "w-40" : "w-24")} />
                    </TableCell>
                  ))}
                  <TableCell className="pr-4">
                    <div className="flex justify-end gap-2">
                      <Skeleton className="h-7 w-7 rounded-md" />
                      {deleteRecord ? <Skeleton className="h-7 w-7 rounded-md" /> : null}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            ) : filteredData.length === 0 ? (
              <TableRow><TableCell colSpan={columns.length + 2} className="py-16 text-center text-sm text-slate-400">暂无数据，点击右上角按钮开始录入</TableCell></TableRow>
            ) : (
              pagedData.map((row, index) => (
                <TableRow key={resolveRowId(row) || index} className="border-slate-100 hover:bg-slate-50/80 dark:border-slate-800 dark:hover:bg-slate-900/80">
                  <TableCell className="text-xs text-slate-400">{(page - 1) * pageSize + index + 1}</TableCell>
                  {columns.map((column) => (
                    <TableCell key={column.key} className="max-w-[24rem] whitespace-normal break-words text-sm text-slate-700 dark:text-slate-200">
                      {column.render ? column.render(row[column.key], row) : (row[column.key] ? String(row[column.key]) : <span className="text-slate-300">—</span>)}
                    </TableCell>
                  ))}
                  <TableCell className="pr-4 text-right">
                    <div className="flex justify-end gap-1">
                      {fetchRecord ? (
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => openView(row)}
                          disabled={recordLoadingId === resolveRowId(row)}
                          className="h-7 w-7 text-slate-500 hover:text-slate-700"
                        >
                          <Eye className="h-3.5 w-3.5" />
                        </Button>
                      ) : null}
                      <Button
                        size="icon"
                        variant="ghost"
                        onClick={() => openEdit(row)}
                        disabled={recordLoadingId === resolveRowId(row)}
                        className="h-7 w-7 text-slate-500 hover:text-slate-700"
                      >
                        <Pencil className="h-3.5 w-3.5" />
                      </Button>
                      {deleteRecord ? (
                        <Button size="icon" variant="ghost" onClick={() => confirmDelete(row)} className="h-7 w-7 text-slate-400 hover:text-red-500"><Trash2 className="h-3.5 w-3.5" /></Button>
                      ) : null}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
      <div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <p className="text-xs text-slate-400">共 {filteredData.length} 条记录，第 {page}/{totalPages} 页</p>
        <div className="flex items-center gap-3">
          <Select value={String(pageSize)} onValueChange={(value) => setPageSize(Number(value))}>
            <SelectTrigger className="h-8 w-[110px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="10">10 / 页</SelectItem>
              <SelectItem value="20">20 / 页</SelectItem>
              <SelectItem value="50">50 / 页</SelectItem>
            </SelectContent>
          </Select>
          <Pagination className="mx-0 w-auto justify-end">
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page <= 1} />
              </PaginationItem>
              {Array.from({ length: totalPages }).slice(0, 5).map((_, idx) => {
                const pageNumber = idx + 1;
                return (
                  <PaginationItem key={pageNumber}>
                    <PaginationLink isActive={pageNumber === page} onClick={() => setPage(pageNumber)}>{pageNumber}</PaginationLink>
                  </PaginationItem>
                );
              })}
              <PaginationItem>
                <PaginationNext onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page >= totalPages} />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      </div>

      {useEnhancedDialog ? (
        <EnhancedDialog open={open} onOpenChange={setOpen}>
          <EnhancedDialogContent
            title={formDialogTitle}
            defaultWidth={960}
            defaultHeight={720}
            minHeight={480}
          >
            <DialogBody>
              <p className="mb-4 text-sm text-muted-foreground">请填写以下字段，带 * 号为必填项。</p>
              {formFieldsGrid}
            </DialogBody>
            <EnhancedDialogFooter className="flex justify-end gap-2">
              {formDialogFooter}
            </EnhancedDialogFooter>
          </EnhancedDialogContent>
        </EnhancedDialog>
      ) : (
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{formDialogTitle}</DialogTitle>
              <DialogDescription>请填写以下字段，带 * 号为必填项。</DialogDescription>
            </DialogHeader>
            <div className="py-2">{formFieldsGrid}</div>
            <DialogFooter className="mt-2">{formDialogFooter}</DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {useEnhancedDialog ? (
        <EnhancedDialog open={Boolean(deletingRow)} onOpenChange={(openState) => { if (!openState) setDeletingRow(null); }}>
          <EnhancedDialogContent title="确认删除" defaultWidth={480} defaultHeight={260} minHeight={220}>
            <DialogBody>
              <p className="text-sm text-muted-foreground">{deleteDialogDescription}</p>
            </DialogBody>
            <EnhancedDialogFooter className="flex justify-end gap-2">
              {deleteDialogFooter}
            </EnhancedDialogFooter>
          </EnhancedDialogContent>
        </EnhancedDialog>
      ) : (
        <Dialog open={Boolean(deletingRow)} onOpenChange={(openState) => { if (!openState) setDeletingRow(null); }}>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle>确认删除</DialogTitle>
              <DialogDescription>{deleteDialogDescription}</DialogDescription>
            </DialogHeader>
            <DialogFooter>{deleteDialogFooter}</DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{title}详情</DialogTitle>
            <DialogDescription>来自 GET 接口的完整记录信息</DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-1 gap-4 py-2 md:grid-cols-2">
            {fields.map((field) => (
              <div key={field.key} className={field.colSpan === 2 || field.type === "textarea" ? "md:col-span-2" : ""}>
                <p className="text-xs font-medium text-slate-500 dark:text-slate-400">{field.label}</p>
                <p className="mt-1 whitespace-pre-wrap break-words text-sm text-slate-800 dark:text-slate-100">
                  {detailRow?.[field.key] ? String(detailRow[field.key]) : "—"}
                </p>
              </div>
            ))}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDetailOpen(false)}>关闭</Button>
            {detailRow ? (
              <Button onClick={() => { setDetailOpen(false); void openEdit(detailRow); }}>编辑</Button>
            ) : null}
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
