import { useEffect, useRef, useState } from "react";
import Modal from "./Modal";
import { adminFetch } from "./adminApi";
import { copyText, type LinkType } from "./utils";
import { useToast } from "./Toast";

type QRResponse = {
  qrDataUrl: string;
  [urlKey: string]: string;
};

const CFG: Record<LinkType, { path: (id: string) => string; urlKey: string; nameKey: string; label: string }> = {
  stamp: { path: (id) => `/stamps/${id}/qrcode`, urlKey: "collectUrl", nameKey: "stampName", label: "Stamp" },
  article: { path: (id) => `/articles/${id}/qrcode`, urlKey: "articleUrl", nameKey: "articleTitle", label: "Article" },
  music: { path: (id) => `/music/${id}/qrcode`, urlKey: "musicUrl", nameKey: "musicTitle", label: "Music" },
};

type Props = {
  open: boolean;
  type: LinkType;
  id: string | null;
  onClose: () => void;
};

export default function QRCodeModal({ open, type, id, onClose }: Props) {
  const cfg = CFG[type];
  const [data, setData] = useState<{ qrDataUrl: string; url: string; name: string } | null>(null);
  const [loading, setLoading] = useState(false);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const toast = useToast();

  useEffect(() => {
    if (!open || !id) {
      setData(null);
      return;
    }
    setLoading(true);
    adminFetch<QRResponse>(cfg.path(id))
      .then((res) =>
        setData({
          qrDataUrl: res.qrDataUrl,
          url: res[cfg.urlKey],
          name: res[cfg.nameKey],
        }),
      )
      .finally(() => setLoading(false));
  }, [open, id, cfg]);

  useEffect(() => {
    if (!data || !canvasRef.current) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    const img = new Image();
    img.onload = () => {
      const pad = 24;
      const textH = 40;
      canvas.width = img.width + pad * 2;
      canvas.height = img.height + pad * 2 + textH;
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, pad, pad);
      ctx.fillStyle = "#4a4553";
      ctx.font = "12px sans-serif";
      ctx.textAlign = "center";
      ctx.fillText(data.url, canvas.width / 2, img.height + pad * 2 + 14);
    };
    img.src = data.qrDataUrl;
  }, [data]);

  const handleCopy = async () => {
    if (!data) return;
    await copyText(data.url);
    toast.show("链接已复制");
  };

  const handleDownload = () => {
    if (!canvasRef.current || !data) return;
    const link = document.createElement("a");
    link.download = `${data.name}-二维码.png`;
    link.href = canvasRef.current.toDataURL("image/png");
    link.click();
  };

  return (
    <Modal open={open} onClose={onClose} size="sm" eyebrow={cfg.label} title={data?.name ?? "点位链接"}>
      <div className="px-7 py-7">
        {loading || !data ? (
          <div className="py-16 flex justify-center">
            <div className="w-8 h-8 border-2 border-[var(--gold)] border-t-transparent rounded-full animate-spin" />
          </div>
        ) : (
          <>
            <div className="relative mx-auto w-56 h-56">
              <span className="absolute -top-1 -left-1 w-4 h-4 border-t-2 border-l-2 border-[var(--gold)]/50" />
              <span className="absolute -top-1 -right-1 w-4 h-4 border-t-2 border-r-2 border-[var(--gold)]/50" />
              <span className="absolute -bottom-1 -left-1 w-4 h-4 border-b-2 border-l-2 border-[var(--gold)]/50" />
              <span className="absolute -bottom-1 -right-1 w-4 h-4 border-b-2 border-r-2 border-[var(--gold)]/50" />
              <div
                className="w-full h-full rounded-xl bg-white p-3"
                style={{ boxShadow: "0 12px 40px rgba(16,16,30,0.12)" }}
              >
                <img src={data.qrDataUrl} alt="二维码" className="w-full h-full" />
              </div>
            </div>

            <div className="mt-7 text-center">
              <p className="text-[10px] tracking-[0.3em] uppercase text-[var(--text-muted)] mb-2">URL</p>
              <p className="text-xs text-[var(--text-secondary)] break-all select-all font-mono leading-relaxed px-2">
                {data.url}
              </p>
            </div>

            <canvas ref={canvasRef} className="hidden" />

            <div className="mt-7 flex gap-3">
              <button
                onClick={handleCopy}
                className="flex-1 py-3 rounded-xl text-sm font-medium text-white transition-all hover:brightness-110"
                style={{
                  backgroundColor: "var(--terracotta)",
                  boxShadow: "0 6px 18px rgba(199,91,57,0.3)",
                }}
              >
                复制链接
              </button>
              <button
                onClick={handleDownload}
                className="flex-1 py-3 rounded-xl text-sm font-medium border border-[var(--border-default)] text-[var(--text-secondary)] bg-white hover:bg-[var(--bg-paper)] transition-colors"
              >
                下载二维码
              </button>
            </div>

            <p className="mt-5 text-[11px] text-[var(--text-muted)] text-center leading-relaxed">
              点位主要通过 NFC 触碰分发，二维码作为备用
            </p>
          </>
        )}
      </div>
    </Modal>
  );
}
