"use client";

import { useCallback, useState } from "react";
import { ArrowDown, ArrowUp, Plus, Trash2, Upload } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
} from "@/components/common/shadcn-enhanced";
import { appendListItems, normalizeNewItems, replaceListItems } from "../api";

type ListItemPanelProps = {
  listDbId: string;
  items: string[];
  onItemsChange: (items: string[]) => void;
};

export function ListItemPanel({ listDbId, items, onItemsChange }: ListItemPanelProps) {
  const [addOpen, setAddOpen] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [newItem, setNewItem] = useState("");
  const [importText, setImportText] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deleteIndex, setDeleteIndex] = useState<number | null>(null);

  const runAction = useCallback(async (action: () => Promise<{ data?: string[] }>) => {
    setSaving(true);
    setError(null);
    try {
      const result = await action();
      onItemsChange(result.data ?? []);
    } catch (event) {
      setError(event instanceof Error ? event.message : "操作失败");
    } finally {
      setSaving(false);
    }
  }, [onItemsChange]);

  const handleAddItem = async () => {
    const added = normalizeNewItems(items, [newItem]);
    await runAction(async () => appendListItems(listDbId, added));
    setNewItem("");
    setAddOpen(false);
  };

  const handleImport = async () => {
    const lines = importText.split(/\r?\n/);
    const added = normalizeNewItems(items, lines);
    await runAction(async () => appendListItems(listDbId, added));
    setImportText("");
    setImportOpen(false);
  };

  const handleDelete = async () => {
    if (deleteIndex === null) return;
    const nextItems = items.filter((_, index) => index !== deleteIndex);
    await runAction(async () => replaceListItems(listDbId, nextItems));
    setDeleteIndex(null);
  };

  const moveItem = async (index: number, direction: -1 | 1) => {
    const target = index + direction;
    if (target < 0 || target >= items.length) return;
    const nextItems = [...items];
    [nextItems[index], nextItems[target]] = [nextItems[target], nextItems[index]];
    await runAction(async () => replaceListItems(listDbId, nextItems));
  };

  return (
    <div className="rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950">
      <div className="flex flex-col gap-3 border-b border-slate-200 px-4 py-3 sm:flex-row sm:items-center sm:justify-between dark:border-slate-800">
        <div>
          <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-50">列表项 (list_item)</h3>
          <p className="mt-0.5 text-xs text-slate-500 dark:text-slate-400">同一列表内项值不可重复；删除与排序通过 PUT 整表替换实现</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button size="sm" className="gap-1.5" onClick={() => setAddOpen(true)} disabled={saving}>
            <Plus className="h-3.5 w-3.5" />
            新增项
          </Button>
          <Button size="sm" variant="outline" className="gap-1.5" onClick={() => setImportOpen(true)} disabled={saving}>
            <Upload className="h-3.5 w-3.5" />
            批量导入
          </Button>
        </div>
      </div>

      {error ? (
        <div className="mx-4 mt-3 rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive">
          {error}
        </div>
      ) : null}

      <Table>
        <TableHeader>
          <TableRow className="border-slate-200 bg-slate-50 dark:border-slate-800 dark:bg-slate-900">
            <TableHead className="w-12 text-xs">#</TableHead>
            <TableHead className="text-xs">项值 (item)</TableHead>
            <TableHead className="w-36 text-right text-xs">操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {items.length === 0 ? (
            <TableRow>
              <TableCell colSpan={3} className="py-12 text-center text-sm text-slate-400">
                暂无列表项，可新增或批量导入
              </TableCell>
            </TableRow>
          ) : (
            items.map((item, index) => (
              <TableRow key={`${item}-${index}`} className="border-slate-100 dark:border-slate-800">
                <TableCell className="text-xs text-slate-400">{index + 1}</TableCell>
                <TableCell className="break-all text-sm text-slate-700 dark:text-slate-200">{item}</TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-1">
                    <Button
                      size="icon"
                      variant="ghost"
                      className="h-7 w-7"
                      disabled={saving || index === 0}
                      onClick={() => moveItem(index, -1)}
                    >
                      <ArrowUp className="h-3.5 w-3.5" />
                    </Button>
                    <Button
                      size="icon"
                      variant="ghost"
                      className="h-7 w-7"
                      disabled={saving || index === items.length - 1}
                      onClick={() => moveItem(index, 1)}
                    >
                      <ArrowDown className="h-3.5 w-3.5" />
                    </Button>
                    <Button
                      size="icon"
                      variant="ghost"
                      className="h-7 w-7 text-slate-400 hover:text-red-500"
                      disabled={saving}
                      onClick={() => setDeleteIndex(index)}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>

      <Dialog open={addOpen} onOpenChange={setAddOpen}>
        <DialogContent title="新增列表项" defaultWidth={520} defaultHeight={320} minHeight={280}>
          <DialogBody>
            <p className="mb-3 text-sm text-muted-foreground">填写目标对象 ID 或文本值，同一列表内不可重复</p>
            <Label htmlFor="new-list-item" className="mb-1.5 block text-sm">项值</Label>
            <Input
              id="new-list-item"
              value={newItem}
              onChange={(event) => setNewItem(event.target.value)}
              placeholder="如 germplasm ID、study ID 或备注文本"
            />
          </DialogBody>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAddOpen(false)}>取消</Button>
            <Button onClick={handleAddItem} disabled={saving || !newItem.trim()}>
              {saving ? "保存中..." : "确认添加"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={importOpen} onOpenChange={setImportOpen}>
        <DialogContent title="批量导入列表项" defaultWidth={560} defaultHeight={480} minHeight={360}>
          <DialogBody>
            <p className="mb-3 text-sm text-muted-foreground">每行一个项值，重复项将拒绝导入</p>
            <Textarea
              value={importText}
              onChange={(event) => setImportText(event.target.value)}
              rows={8}
              placeholder={"GERM-001\nGERM-002\nstudy-2026-spring"}
              className="resize-none font-mono text-sm"
            />
          </DialogBody>
          <DialogFooter>
            <Button variant="outline" onClick={() => setImportOpen(false)}>取消</Button>
            <Button onClick={handleImport} disabled={saving || !importText.trim()}>
              {saving ? "导入中..." : "确认导入"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={deleteIndex !== null} onOpenChange={(open) => !open && setDeleteIndex(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>删除列表项</AlertDialogTitle>
            <AlertDialogDescription>
              确认删除项
              {" "}
              <span className="font-medium text-slate-700 dark:text-slate-200">
                {deleteIndex !== null ? items[deleteIndex] : ""}
              </span>
              {" "}
              吗？此操作通过更新整表数据生效。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={saving}>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={saving} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              {saving ? "删除中..." : "确认删除"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
