import { useState, useEffect, useRef } from "react";
import { useParams, Link } from "react-router-dom";
import { adminFetch } from "./adminApi";

type QRData = {
  qrDataUrl: string;
  collectUrl: string;
  stampName: string;
};

export default function StampQRCode() {
  const { id } = useParams();
  const [data, setData] = useState<QRData | null>(null);
  const [loading, setLoading] = useState(true);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (!id) return;
    adminFetch<QRData>(`/stamps/${id}/qrcode`)
      .then(setData)
      .finally(() => setLoading(false));
  }, [id]);

  // Render composite image (QR code + URL text) to canvas
  useEffect(() => {
    if (!data || !canvasRef.current) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d")!;
    const img = new Image();
    img.onload = () => {
      const padding = 20;
      const textHeight = 40;
      canvas.width = img.width + padding * 2;
      canvas.height = img.height + padding * 2 + textHeight;

      // White background
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // QR code
      ctx.drawImage(img, padding, padding);

      // URL text below
      ctx.fillStyle = "#666666";
      ctx.font = "12px sans-serif";
      ctx.textAlign = "center";
      ctx.fillText(data.collectUrl, canvas.width / 2, img.height + padding * 2 + 12);
    };
    img.src = data.qrDataUrl;
  }, [data]);

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

  if (loading) return <p className="text-gray-500">加载中...</p>;
  if (!data) return <p className="text-gray-500">图章不存在</p>;

  return (
    <div className="max-w-md">
      <div className="flex items-center gap-2 mb-4">
        <Link to="/admin/stamps" className="text-gray-400 hover:text-gray-600">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M15 18l-6-6 6-6" />
          </svg>
        </Link>
        <h2 className="text-lg font-semibold text-gray-800">{data.stampName} — 二维码</h2>
      </div>

      <div className="bg-white rounded-lg border border-gray-200 p-6 text-center space-y-4">
        {/* QR code display */}
        <div className="inline-block">
          <img src={data.qrDataUrl} alt="二维码" className="w-64 h-64" />
        </div>

        {/* URL display */}
        <p className="text-xs text-gray-500 break-all select-all">{data.collectUrl}</p>

        {/* Hidden canvas for composite download */}
        <canvas ref={canvasRef} className="hidden" />

        <button
          onClick={handleDownload}
          className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700"
        >
          下载二维码（含链接）
        </button>
      </div>
    </div>
  );
}
