import { useState, useEffect } from "react";
import { adminFetch } from "./adminApi";
import { useToast } from "./Toast";
import { copyItemLink } from "./utils";
import StampForm from "./StampForm";
import QRCodeModal from "./QRCodeModal";
import PageHeader, {
  PrimaryButton,
  StatusChip,
  ActionButton,
  EmptyState,
  LoadingBlock,
  IconEdit,
  IconCopy,
  IconQR,
  IconDelete,
} from "./PageHeader";

type Stamp = {
  id: string;
  name: string;
  note: string | null;
  imageColor: string;
  imageGrey: string;
  sortOrder: number;
  enabled: boolean;
};

export default function StampList() {
  const toast = useToast();
  const [stamps, setStamps] = useState<Stamp[]>([]);
  const [loading, setLoading] = useState(true);

  const [formState, setFormState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });
  const [qrState, setQrState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });

  const fetchStamps = async () => {
    try {
      const data = await adminFetch<Stamp[]>("/stamps");
      setStamps(data);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStamps();
  }, []);

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`确定删除图章「${name}」？`)) return;
    try {
      await adminFetch(`/stamps/${id}`, { method: "DELETE" });
      toast.show("已删除");
      fetchStamps();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "删除失败", "error");
    }
  };

  const handleToggle = async (id: string, enabled: boolean) => {
    await adminFetch(`/stamps/${id}`, {
      method: "PUT",
      body: JSON.stringify({ enabled: !enabled }),
    });
    fetchStamps();
  };

  const handleCopyLink = async (id: string) => {
    try {
      await copyItemLink("stamp", id);
      toast.show("链接已复制");
    } catch {
      toast.show("复制失败", "error");
    }
  };

  return (
    <>
      <PageHeader
        eyebrow="02 · Stamps"
        title="图章管理"
        caption="收集图章、生成点位 NFC 链接与备用二维码"
        action={
          <PrimaryButton onClick={() => setFormState({ open: true, id: null })}>添加图章</PrimaryButton>
        }
      />

      {loading ? (
        <LoadingBlock />
      ) : (
        <TableCard>
          {stamps.length === 0 ? (
            <EmptyState
              message="尚未创建图章"
              action={
                <PrimaryButton onClick={() => setFormState({ open: true, id: null })}>
                  添加第一枚图章
                </PrimaryButton>
              }
            />
          ) : (
            <table className="w-full">
              <thead>
                <TableHeadRow cols={["图章", "名称 · 备注", "排序", "状态", "操作"]} />
              </thead>
              <tbody>
                {stamps.map((stamp, i) => (
                  <tr
                    key={stamp.id}
                    className="border-t border-[var(--border-muted)] hover:bg-white/60 transition-colors animate-admin-row"
                    style={{ animationDelay: `${Math.min(i, 12) * 0.03}s` }}
                  >
                    <td className="px-5 py-4 w-[90px]">
                      <div className="w-12 h-12 rounded-full bg-white border border-[var(--border-muted)] overflow-hidden flex items-center justify-center shadow-sm">
                        {stamp.imageColor ? (
                          <img src={stamp.imageColor} alt="" className="w-[92%] h-[92%] object-contain" />
                        ) : (
                          <span className="text-[9px] tracking-[0.2em] uppercase text-[var(--text-muted)]/60">
                            No image
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <p className="text-[15px] font-medium text-[var(--text-primary)]">{stamp.name}</p>
                      {stamp.note && (
                        <p className="text-xs text-[var(--text-muted)] mt-0.5 max-w-[360px] truncate">
                          {stamp.note}
                        </p>
                      )}
                    </td>
                    <td className="px-5 py-4 text-center w-[80px]">
                      <span
                        className="text-[13px] text-[var(--text-secondary)]"
                        style={{ fontFamily: "'Playfair Display', serif" }}
                      >
                        {stamp.sortOrder}
                      </span>
                    </td>
                    <td className="px-5 py-4 text-center w-[110px]">
                      <StatusChip enabled={stamp.enabled} onClick={() => handleToggle(stamp.id, stamp.enabled)} />
                    </td>
                    <td className="px-5 py-4 w-[180px]">
                      <div className="flex items-center justify-end gap-1">
                        <ActionButton title="编辑" onClick={() => setFormState({ open: true, id: stamp.id })}>
                          {IconEdit}
                        </ActionButton>
                        <ActionButton title="复制链接" onClick={() => handleCopyLink(stamp.id)}>
                          {IconCopy}
                        </ActionButton>
                        <ActionButton title="二维码" onClick={() => setQrState({ open: true, id: stamp.id })}>
                          {IconQR}
                        </ActionButton>
                        <ActionButton
                          title="删除"
                          variant="danger"
                          onClick={() => handleDelete(stamp.id, stamp.name)}
                        >
                          {IconDelete}
                        </ActionButton>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </TableCard>
      )}

      <StampForm
        open={formState.open}
        id={formState.id}
        onClose={() => setFormState({ open: false, id: null })}
        onSaved={fetchStamps}
      />
      <QRCodeModal
        open={qrState.open}
        type="stamp"
        id={qrState.id}
        onClose={() => setQrState({ open: false, id: null })}
      />
    </>
  );
}

/* ————— Shared table pieces (also used by other list pages) ————— */

export function TableCard({ children }: { children: React.ReactNode }) {
  return (
    <div
      className="rounded-2xl bg-white/70 border border-[var(--border-muted)] overflow-hidden"
      style={{ boxShadow: "0 1px 2px rgba(16,16,30,0.04), 0 8px 24px rgba(16,16,30,0.04)" }}
    >
      {children}
    </div>
  );
}

export function TableHeadRow({ cols }: { cols: string[] }) {
  return (
    <tr className="bg-[var(--bg-paper)]/60">
      {cols.map((c, i) => (
        <th
          key={c}
          className={`px-5 py-3.5 text-[10px] tracking-[0.25em] uppercase text-[var(--text-muted)] font-medium ${
            i === cols.length - 1 ? "text-right" : i === 0 ? "text-left" : "text-left"
          }`}
          style={{ fontFamily: "'Playfair Display', serif" }}
        >
          {i === cols.length - 1 ? <span className="inline-block pr-2">{c}</span> : c}
        </th>
      ))}
    </tr>
  );
}
