"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Autocomplete,
  Button,
  Calendar,
  Chip,
  DateField,
  DatePicker,
  EmptyState,
  Input,
  InputGroup,
  Label,
  ListBox,
  Modal,
  SearchField,
  Select,
  Spinner,
  Table,
  TextField,
  useFilter,
} from "@heroui/react";
import { parseDate } from "@internationalized/date";
import { ArrowRotateRight, Pencil, Plus, TrashBin } from "@gravity-ui/icons";
import { LayoutGrid, List } from "lucide-react";
import { api, type IdTag, type UserRow } from "@/lib/api";
import { useSession } from "@/lib/auth-client";
import dayjs from "@/lib/dayjs";
import { IdTagCard } from "@/components/id-tag-card";

const statusColorMap: Record<string, "success" | "danger" | "warning"> = {
  Accepted: "success",
  Blocked: "danger",
  Expired: "warning",
  Invalid: "danger",
  ConcurrentTx: "warning",
};

type FormState = {
  idTag: string;
  status: string;
  expiryDate: string;
  parentIdTag: string;
  userId: string;
  balance: string;
  cardLayout: string;
  cardSkin: string;
};

const emptyForm: FormState = {
  idTag: "",
  status: "Accepted",
  expiryDate: "",
  parentIdTag: "",
  userId: "",
  balance: "0",
  cardLayout: "around",
  cardSkin: "circles",
};

const STATUS_OPTIONS = ["Accepted", "Blocked", "Expired", "Invalid", "ConcurrentTx"] as const;

/** 将「元」字符串转为分（整数），无效时返回 0 */
function yuanToFen(yuan: string): number {
  const n = parseFloat(yuan);
  return isNaN(n) ? 0 : Math.round(n * 100);
}

/** 将分（整数）格式化为「元」字符串 */
function fenToYuan(fen: number): string {
  return (fen / 100).toFixed(2);
}

function UserAutocomplete({
  userId,
  onChange,
  users,
}: {
  userId: string;
  onChange: (id: string) => void;
  users: UserRow[];
}) {
  const { contains } = useFilter({ sensitivity: "base" });
  return (
    <Autocomplete
      fullWidth
      placeholder="搜索用户"
      selectionMode="single"
      value={userId || null}
      onChange={(key) => onChange(key ? String(key) : "")}
    >
      <Autocomplete.Trigger>
        <Autocomplete.Value>
          {({ isPlaceholder, state }: any) => {
            if (isPlaceholder || !state.selectedItems?.length)
              return <span className="text-muted">不分配</span>;
            const u = users.find((u) => u.id === state.selectedItems[0]?.key);
            return u ? <span>{u.name ?? u.username ?? u.email}</span> : null;
          }}
        </Autocomplete.Value>
        <Autocomplete.ClearButton />
        <Autocomplete.Indicator />
      </Autocomplete.Trigger>
      <Autocomplete.Popover>
        <Autocomplete.Filter filter={contains}>
          <SearchField autoFocus name="userSearch" variant="secondary">
            <SearchField.Group>
              <SearchField.SearchIcon />
              <SearchField.Input placeholder="搜索姓名或邮箱" />
              <SearchField.ClearButton />
            </SearchField.Group>
          </SearchField>
          <ListBox renderEmptyState={() => <EmptyState>无匹配用户</EmptyState>}>
            {users.map((u) => (
              <ListBox.Item
                key={u.id}
                id={u.id}
                textValue={`${u.name ?? u.username ?? ""} ${u.email}`}
              >
                <span className="font-medium">{u.name ?? u.username ?? u.email}</span>
                <span className="ml-1.5 text-xs text-muted">{u.email}</span>
                <ListBox.ItemIndicator />
              </ListBox.Item>
            ))}
          </ListBox>
        </Autocomplete.Filter>
      </Autocomplete.Popover>
    </Autocomplete>
  );
}

function ParentTagAutocomplete({
  value,
  onChange,
  tags,
  excludeTag,
}: {
  value: string;
  onChange: (v: string) => void;
  tags: IdTag[];
  excludeTag?: string;
}) {
  const { contains } = useFilter({ sensitivity: "base" });
  const options = tags.filter((t) => t.idTag !== excludeTag);
  return (
    <Autocomplete
      fullWidth
      placeholder="搜索卡号"
      selectionMode="single"
      value={value || null}
      onChange={(key) => onChange(key ? String(key) : "")}
    >
      <Autocomplete.Trigger>
        <Autocomplete.Value>
          {({ isPlaceholder, state }: any) => {
            if (isPlaceholder || !state.selectedItems?.length)
              return <span className="text-muted">无</span>;
            return <span className="font-mono">{state.selectedItems[0]?.key}</span>;
          }}
        </Autocomplete.Value>
        <Autocomplete.ClearButton />
        <Autocomplete.Indicator />
      </Autocomplete.Trigger>
      <Autocomplete.Popover>
        <Autocomplete.Filter filter={contains}>
          <SearchField autoFocus name="parentTagSearch" variant="secondary">
            <SearchField.Group>
              <SearchField.SearchIcon />
              <SearchField.Input placeholder="搜索卡号" />
              <SearchField.ClearButton />
            </SearchField.Group>
          </SearchField>
          <ListBox renderEmptyState={() => <EmptyState>无匹配卡号</EmptyState>}>
            {options.map((t) => (
              <ListBox.Item key={t.idTag} id={t.idTag} textValue={t.idTag}>
                <span className="font-mono">{t.idTag}</span>
                <ListBox.ItemIndicator />
              </ListBox.Item>
            ))}
          </ListBox>
        </Autocomplete.Filter>
      </Autocomplete.Popover>
    </Autocomplete>
  );
}

function generateIdTag(): string {
  const chars = "0123456789ABCDEF";
  let result = "";
  for (let i = 0; i < 8; i++) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
}

function TagFormBody({
  form,
  setForm,
  isEdit,
  users,
  tags,
}: {
  form: FormState;
  setForm: (f: FormState) => void;
  isEdit: boolean;
  users: UserRow[];
  tags: IdTag[];
}) {
  return (
    <>
      <TextField fullWidth>
        <div className="flex items-center justify-between">
          <Label className="text-sm font-medium">{isEdit ? "卡号" : "卡号 (idTag)"}</Label>
          {!isEdit && (
            <button
              type="button"
              className="text-xs text-accent hover:underline"
              onClick={() => setForm({ ...form, idTag: generateIdTag() })}
            >
              随机生成
            </button>
          )}
        </div>
        <Input
          disabled={isEdit}
          className="font-mono"
          placeholder="e.g. RFID001"
          value={form.idTag}
          onChange={(e) => setForm({ ...form, idTag: e.target.value })}
        />
      </TextField>
      <div className="flex flex-col gap-1">
        <Label className="text-sm font-medium">状态</Label>
        <Select
          fullWidth
          selectedKey={form.status}
          onSelectionChange={(key) => setForm({ ...form, status: String(key) })}
        >
          <Select.Trigger>
            <Select.Value />
            <Select.Indicator />
          </Select.Trigger>
          <Select.Popover>
            <ListBox>
              {STATUS_OPTIONS.map((s) => (
                <ListBox.Item key={s} id={s}>
                  {s}
                </ListBox.Item>
              ))}
            </ListBox>
          </Select.Popover>
        </Select>
      </div>
      <div className="flex flex-col gap-1">
        <Label className="text-sm font-medium">有效期</Label>
        <DatePicker
          value={form.expiryDate ? parseDate(form.expiryDate) : null}
          onChange={(date) => setForm({ ...form, expiryDate: date ? date.toString() : "" })}
        >
          <DateField.Group fullWidth>
            <DateField.InputContainer>
              <DateField.Input>
                {(segment) => <DateField.Segment segment={segment} />}
              </DateField.Input>
            </DateField.InputContainer>
            <DateField.Suffix>
              <DatePicker.Trigger>
                <DatePicker.TriggerIndicator />
              </DatePicker.Trigger>
            </DateField.Suffix>
          </DateField.Group>
          <DatePicker.Popover>
            <Calendar>
              <Calendar.Header>
                <Calendar.NavButton slot="previous" />
                <Calendar.Heading />
                <Calendar.NavButton slot="next" />
              </Calendar.Header>
              <Calendar.Grid>
                <Calendar.GridHeader>
                  {(day) => <Calendar.HeaderCell>{day}</Calendar.HeaderCell>}
                </Calendar.GridHeader>
                <Calendar.GridBody>
                  {(date) => (
                    <Calendar.Cell date={date}>
                      {({ formattedDate }) => (
                        <>
                          {formattedDate}
                          <Calendar.CellIndicator />
                        </>
                      )}
                    </Calendar.Cell>
                  )}
                </Calendar.GridBody>
              </Calendar.Grid>
            </Calendar>
          </DatePicker.Popover>
        </DatePicker>
      </div>
      <div className="flex flex-col gap-1">
        <Label className="text-sm font-medium">父卡号</Label>
        <ParentTagAutocomplete
          value={form.parentIdTag}
          onChange={(v) => setForm({ ...form, parentIdTag: v })}
          tags={tags}
          excludeTag={isEdit ? form.idTag : undefined}
        />
      </div>
      <TextField fullWidth>
        <Label className="text-sm font-medium">余额</Label>
        <InputGroup>
          <InputGroup.Prefix>￥</InputGroup.Prefix>
          <InputGroup.Input
            placeholder="0.00"
            min="0"
            step="0.01"
            type="number"
            value={form.balance}
            onChange={(e) => setForm({ ...form, balance: e.target.value })}
          />
          <InputGroup.Suffix>CNY</InputGroup.Suffix>
        </InputGroup>
      </TextField>
      <div className="flex flex-col gap-1">
        <Label className="text-sm font-medium">关联用户</Label>
        <UserAutocomplete
          userId={form.userId}
          onChange={(id) => setForm({ ...form, userId: id })}
          users={users}
        />
      </div>
      <div className="flex flex-col gap-1">
        <Label className="text-sm font-medium">卡面布局</Label>
        <Select
          fullWidth
          selectedKey={form.cardLayout}
          onSelectionChange={(key) => setForm({ ...form, cardLayout: String(key) })}
        >
          <Select.Trigger>
            <Select.Value />
            <Select.Indicator />
          </Select.Trigger>
          <Select.Popover>
            <ListBox>
              <ListBox.Item key="around" id="around">
                四周
              </ListBox.Item>
              <ListBox.Item key="center" id="center">
                卡号居中
              </ListBox.Item>
            </ListBox>
          </Select.Popover>
        </Select>
      </div>
      <div className="flex flex-col gap-1">
        <Label className="text-sm font-medium">卡面皮肤</Label>
        <Select
          fullWidth
          selectedKey={form.cardSkin}
          onSelectionChange={(key) => setForm({ ...form, cardSkin: String(key) })}
        >
          <Select.Trigger>
            <Select.Value />
            <Select.Indicator />
          </Select.Trigger>
          <Select.Popover>
            <ListBox>
              <ListBox.Item key="circles" id="circles">
                装饰圆形
              </ListBox.Item>
              <ListBox.Item key="line" id="line">
                斜线纹理
              </ListBox.Item>
              <ListBox.Item key="glow" id="glow">
                渐变光晕
              </ListBox.Item>
              <ListBox.Item key="vip" id="vip">
                黑金 VIP
              </ListBox.Item>
              <ListBox.Item key="redeye" id="redeye">
                赤眼
              </ListBox.Item>
            </ListBox>
          </Select.Popover>
        </Select>
      </div>
    </>
  );
}

export default function IdTagsPage() {
  const { data: sessionData } = useSession();
  const isAdmin = sessionData?.user?.role === "admin";
  const [editing, setEditing] = useState<IdTag | null>(null);
  const [form, setForm] = useState<FormState>(emptyForm);
  const [saving, setSaving] = useState(false);
  const [deletingTag, setDeletingTag] = useState<string | null>(null);
  const [claiming, setClaiming] = useState(false);
  const [viewMode, setViewMode] = useState<"table" | "grid">("table");

  const {
    data: idTagsData,
    isPending: loading,
    isFetching: refreshing,
    refetch,
  } = useQuery({
    queryKey: ["idTags", "withUsers"],
    queryFn: async () => {
      const [tagList, userList] = await Promise.all([
        api.idTags.list(),
        api.users.list().catch(() => [] as UserRow[]),
      ]);
      return { tags: tagList, users: userList };
    },
  });

  const tags = idTagsData?.tags ?? [];
  const users = idTagsData?.users ?? [];

  const handleClaim = async () => {
    setClaiming(true);
    try {
      await api.idTags.claim();
      await refetch();
    } finally {
      setClaiming(false);
    }
  };

  const openCreate = () => {
    setEditing(null);
    setForm(emptyForm);
  };

  const openEdit = (tag: IdTag) => {
    setEditing(tag);
    setForm({
      idTag: tag.idTag,
      status: tag.status,
      expiryDate: tag.expiryDate ? tag.expiryDate.slice(0, 10) : "",
      parentIdTag: tag.parentIdTag ?? "",
      userId: tag.userId ?? "",
      balance: fenToYuan(tag.balance),
      cardLayout: tag.cardLayout ?? "around",
      cardSkin: tag.cardSkin ?? "circles",
    });
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      if (editing) {
        await api.idTags.update(editing.idTag, {
          status: form.status,
          expiryDate: form.expiryDate || null,
          parentIdTag: form.parentIdTag || null,
          userId: form.userId || null,
          balance: yuanToFen(form.balance),
          cardLayout: (form.cardLayout as "center" | "around") || null,
          cardSkin: (form.cardSkin as "line" | "circles" | "glow" | "vip" | "redeye") || null,
        });
      } else {
        await api.idTags.create({
          idTag: form.idTag,
          status: form.status,
          expiryDate: form.expiryDate || undefined,
          parentIdTag: form.parentIdTag || undefined,
          userId: form.userId || undefined,
          balance: yuanToFen(form.balance),
          cardLayout: (form.cardLayout as "center" | "around") || undefined,
          cardSkin: (form.cardSkin as "line" | "circles" | "glow" | "vip" | "redeye") || undefined,
        });
      }
      await refetch();
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (idTag: string) => {
    setDeletingTag(idTag);
    try {
      await api.idTags.delete(idTag);
      await refetch();
    } finally {
      setDeletingTag(null);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h1 className="text-xl font-semibold text-foreground">储值卡管理</h1>
          <p className="mt-0.5 text-sm text-muted">共 {tags.length} 张</p>
        </div>
        {isAdmin ? (
          <div className="flex items-center gap-2">
            <Button
              isIconOnly
              size="sm"
              variant="ghost"
              isDisabled={refreshing}
              onPress={() => refetch()}
              aria-label="刷新"
            >
              <ArrowRotateRight className={`size-4 ${refreshing ? "animate-spin" : ""}`} />
            </Button>
            <Button
              isIconOnly
              size="sm"
              variant="ghost"
              onPress={() => setViewMode(viewMode === "table" ? "grid" : "table")}
              aria-label={viewMode === "table" ? "切换到卡片视图" : "切换到列表视图"}
            >
              {viewMode === "table" ? (
                <LayoutGrid className="size-4" />
              ) : (
                <List className="size-4" />
              )}
            </Button>
            <Modal>
              <Button size="sm" variant="secondary" onPress={openCreate}>
                <Plus className="size-4" />
                新增储值卡
              </Button>
              <Modal.Backdrop>
                <Modal.Container scroll="outside">
                  <Modal.Dialog className="sm:max-w-105">
                    <Modal.CloseTrigger />
                    <Modal.Header>
                      <Modal.Heading>新增储值卡</Modal.Heading>
                    </Modal.Header>
                    <Modal.Body className="space-y-3">
                      <TagFormBody
                        form={form}
                        setForm={setForm}
                        isEdit={false}
                        users={users}
                        tags={tags}
                      />
                    </Modal.Body>
                    <Modal.Footer className="flex justify-end gap-2">
                      <Button slot="close" variant="ghost">
                        取消
                      </Button>
                      <Button isDisabled={saving} slot="close" onPress={handleSave}>
                        {saving ? <Spinner size="sm" /> : "创建"}
                      </Button>
                    </Modal.Footer>
                  </Modal.Dialog>
                </Modal.Container>
              </Modal.Backdrop>
            </Modal>
          </div>
        ) : (
          <Button size="sm" variant="secondary" isDisabled={claiming} onPress={handleClaim}>
            <Plus className="size-4" />
            {claiming ? <Spinner size="sm" /> : "申领储值卡"}
          </Button>
        )}
      </div>

      {/* ── Grid view ─────────────────────────────────────────── */}
      {(!isAdmin || viewMode === "grid") && (
        <>
          {loading ? (
            <div className="flex justify-center py-16">
              <Spinner />
            </div>
          ) : tags.length === 0 ? (
            <div className="rounded-2xl border border-border px-6 py-14 text-center text-sm text-muted">
              暂无储值卡
            </div>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {tags.map((tag) => {
                const owner = users.find((u) => u.id === tag.userId);
                return (
                  <div key={tag.idTag} className="space-y-2">
                    <IdTagCard
                      idTag={tag.idTag}
                      balance={tag.balance}
                      layout={tag.cardLayout ?? undefined}
                      skin={tag.cardSkin ?? undefined}
                    />
                    {isAdmin && (
                      <div className="flex items-center justify-between px-1">
                        <div className="flex min-w-0 items-center gap-1.5">
                          <Chip
                            color={statusColorMap[tag.status] ?? "warning"}
                            size="sm"
                            variant="soft"
                          >
                            {tag.status}
                          </Chip>
                          {owner && (
                            <span className="truncate text-xs text-muted">
                              {owner.name ?? owner.username ?? owner.email}
                            </span>
                          )}
                        </div>
                        <div className="flex shrink-0 gap-1">
                          <Modal>
                            <Button
                              isIconOnly
                              size="sm"
                              variant="tertiary"
                              onPress={() => openEdit(tag)}
                            >
                              <Pencil className="size-4" />
                            </Button>
                            <Modal.Backdrop>
                              <Modal.Container scroll="outside">
                                <Modal.Dialog className="sm:max-w-105">
                                  <Modal.CloseTrigger />
                                  <Modal.Header>
                                    <Modal.Heading>编辑储值卡</Modal.Heading>
                                  </Modal.Header>
                                  <Modal.Body className="space-y-3">
                                    <TagFormBody
                                      form={form}
                                      setForm={setForm}
                                      isEdit={true}
                                      users={users}
                                      tags={tags}
                                    />
                                  </Modal.Body>
                                  <Modal.Footer className="flex justify-end gap-2">
                                    <Button slot="close" variant="ghost">
                                      取消
                                    </Button>
                                    <Button isDisabled={saving} slot="close" onPress={handleSave}>
                                      {saving ? <Spinner size="sm" /> : "保存"}
                                    </Button>
                                  </Modal.Footer>
                                </Modal.Dialog>
                              </Modal.Container>
                            </Modal.Backdrop>
                          </Modal>
                          <Modal>
                            <Button
                              isDisabled={deletingTag === tag.idTag}
                              isIconOnly
                              size="sm"
                              variant="danger-soft"
                            >
                              {deletingTag === tag.idTag ? (
                                <Spinner size="sm" />
                              ) : (
                                <TrashBin className="size-4" />
                              )}
                            </Button>
                            <Modal.Backdrop>
                              <Modal.Container scroll="outside">
                                <Modal.Dialog className="sm:max-w-96">
                                  <Modal.CloseTrigger />
                                  <Modal.Header>
                                    <Modal.Heading>确认删除储值卡</Modal.Heading>
                                  </Modal.Header>
                                  <Modal.Body>
                                    <p className="text-sm text-muted">
                                      将永久删除储值卡{" "}
                                      <span className="font-mono font-medium text-foreground">
                                        {tag.idTag}
                                      </span>
                                      ，此操作不可恢复。
                                    </p>
                                  </Modal.Body>
                                  <Modal.Footer className="flex justify-end gap-2">
                                    <Button slot="close" variant="ghost">
                                      取消
                                    </Button>
                                    <Button
                                      slot="close"
                                      variant="danger"
                                      isDisabled={deletingTag === tag.idTag}
                                      onPress={() => handleDelete(tag.idTag)}
                                    >
                                      {deletingTag === tag.idTag ? (
                                        <Spinner size="sm" />
                                      ) : (
                                        "确认删除"
                                      )}
                                    </Button>
                                  </Modal.Footer>
                                </Modal.Dialog>
                              </Modal.Container>
                            </Modal.Backdrop>
                          </Modal>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}

      {/* ── Table view (admin only) ────────────────────────────────── */}
      {isAdmin && viewMode === "table" && (
        <Table>
          <Table.ScrollContainer>
            <Table.Content aria-label="储值卡列表" className="min-w-200">
              <Table.Header>
                <Table.Column isRowHeader>卡号</Table.Column>
                <Table.Column>状态</Table.Column>
                <Table.Column>余额</Table.Column>
                {isAdmin && <Table.Column>关联用户</Table.Column>}
                <Table.Column>有效期</Table.Column>
                <Table.Column>父卡号</Table.Column>
                <Table.Column>创建时间</Table.Column>
                {isAdmin && <Table.Column className="text-end">操作</Table.Column>}
              </Table.Header>
              <Table.Body
                renderEmptyState={() => (
                  <div className="py-8 text-center text-sm text-muted">
                    {loading ? "加载中…" : "暂无储值卡"}
                  </div>
                )}
              >
                {tags.map((tag) => {
                  const owner = users.find((u) => u.id === tag.userId);
                  return (
                    <Table.Row key={tag.idTag} id={tag.idTag}>
                      <Table.Cell className="font-mono font-medium">{tag.idTag}</Table.Cell>
                      <Table.Cell>
                        <Chip
                          color={statusColorMap[tag.status] ?? "warning"}
                          size="sm"
                          variant="soft"
                        >
                          {tag.status}
                        </Chip>
                      </Table.Cell>
                      <Table.Cell className="font-mono">¥{fenToYuan(tag.balance)}</Table.Cell>
                      {isAdmin && (
                        <Table.Cell className="text-sm">
                          {owner ? (
                            <span title={owner.email}>
                              {owner.name ?? owner.username ?? owner.email}
                            </span>
                          ) : (
                            <span className="text-muted">—</span>
                          )}
                        </Table.Cell>
                      )}
                      <Table.Cell>
                        {tag.expiryDate ? (
                          dayjs(tag.expiryDate).format("YYYY/M/D")
                        ) : (
                          <span className="text-muted">—</span>
                        )}
                      </Table.Cell>
                      <Table.Cell className="font-mono">
                        {tag.parentIdTag ?? <span className="text-muted">—</span>}
                      </Table.Cell>
                      <Table.Cell className="text-sm">
                        {dayjs(tag.createdAt).format("YYYY/M/D HH:mm:ss")}
                      </Table.Cell>
                      {isAdmin && (
                        <Table.Cell>
                          <div className="flex justify-end gap-1">
                            {/* Edit button */}
                            <Modal>
                              <Button
                                isIconOnly
                                size="sm"
                                variant="tertiary"
                                onPress={() => openEdit(tag)}
                              >
                                <Pencil className="size-4" />
                              </Button>
                              <Modal.Backdrop>
                                <Modal.Container scroll="outside">
                                  <Modal.Dialog className="sm:max-w-105">
                                    <Modal.CloseTrigger />
                                    <Modal.Header>
                                      <Modal.Heading>编辑储值卡</Modal.Heading>
                                    </Modal.Header>
                                    <Modal.Body className="space-y-3">
                                      <TagFormBody
                                        form={form}
                                        setForm={setForm}
                                        isEdit={true}
                                        users={users}
                                        tags={tags}
                                      />
                                    </Modal.Body>
                                    <Modal.Footer className="flex justify-end gap-2">
                                      <Button slot="close" variant="ghost">
                                        取消
                                      </Button>
                                      <Button isDisabled={saving} slot="close" onPress={handleSave}>
                                        {saving ? <Spinner size="sm" /> : "保存"}
                                      </Button>
                                    </Modal.Footer>
                                  </Modal.Dialog>
                                </Modal.Container>
                              </Modal.Backdrop>
                            </Modal>
                            {/* Delete button */}
                            <Modal>
                              <Button
                                isDisabled={deletingTag === tag.idTag}
                                isIconOnly
                                size="sm"
                                variant="danger-soft"
                              >
                                {deletingTag === tag.idTag ? (
                                  <Spinner size="sm" />
                                ) : (
                                  <TrashBin className="size-4" />
                                )}
                              </Button>
                              <Modal.Backdrop>
                                <Modal.Container scroll="outside">
                                  <Modal.Dialog className="sm:max-w-96">
                                    <Modal.CloseTrigger />
                                    <Modal.Header>
                                      <Modal.Heading>确认删除储值卡</Modal.Heading>
                                    </Modal.Header>
                                    <Modal.Body>
                                      <p className="text-sm text-muted">
                                        将永久删除储值卡{" "}
                                        <span className="font-mono font-medium text-foreground">
                                          {tag.idTag}
                                        </span>
                                        ，此操作不可恢复。
                                      </p>
                                    </Modal.Body>
                                    <Modal.Footer className="flex justify-end gap-2">
                                      <Button slot="close" variant="ghost">
                                        取消
                                      </Button>
                                      <Button
                                        slot="close"
                                        variant="danger"
                                        isDisabled={deletingTag === tag.idTag}
                                        onPress={() => handleDelete(tag.idTag)}
                                      >
                                        {deletingTag === tag.idTag ? (
                                          <Spinner size="sm" />
                                        ) : (
                                          "确认删除"
                                        )}
                                      </Button>
                                    </Modal.Footer>
                                  </Modal.Dialog>
                                </Modal.Container>
                              </Modal.Backdrop>
                            </Modal>
                          </div>
                        </Table.Cell>
                      )}
                    </Table.Row>
                  );
                })}
              </Table.Body>
            </Table.Content>
          </Table.ScrollContainer>
        </Table>
      )}
    </div>
  );
}
