"use client";

/**
 * QrCheckinModal — Admin-side modal that shows a scannable QR code for a
 * given program. Volunteers scan it (camera app or in-app scanner) to be
 * taken straight to the check-in URL.
 *
 * USAGE (inside app/(dashboard)/programs/page.tsx):
 *
 *   import QrCheckinModal from "@/components/QrCheckinModal";
 *   ...
 *   const [qrProgram, setQrProgram] = useState<{ id: string; title: string } | null>(null);
 *   ...
 *   <Button size="sm" variant="secondary" onClick={() => setQrProgram({ id: p.id, title: p.title })}>
 *     <QrCode size={14} /> Attendance QR
 *   </Button>
 *   ...
 *   <QrCheckinModal program={qrProgram} onClose={() => setQrProgram(null)} />
 *
 * Install dependency first:
 *   npm install qrcode
 *   npm install -D @types/qrcode
 */

import { useEffect, useState } from "react";
import QRCode from "qrcode";
import Modal from "@/components/ui/Modal";
import Button from "@/components/ui/Button";
import { Download, RefreshCw } from "lucide-react";

type Props = {
  program: { id: string; title: string } | null;
  onClose: () => void;
};

export default function QrCheckinModal({ program, onClose }: Props) {
  const [dataUrl, setDataUrl] = useState<string>("");
  const [checkinUrl, setCheckinUrl] = useState<string>("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!program) return;

    const url = `${window.location.origin}/portal/checkin/${program.id}`;
    setCheckinUrl(url);
    setLoading(true);

    QRCode.toDataURL(url, {
      width: 480,
      margin: 2,
      color: { dark: "#0F6E56", light: "#FFFFFF" },
    })
      .then(setDataUrl)
      .catch((err) => console.error("Failed to generate QR code:", err))
      .finally(() => setLoading(false));
  }, [program]);

  function downloadQr() {
    if (!dataUrl || !program) return;
    const a = document.createElement("a");
    a.href = dataUrl;
    a.download = `attendance-qr-${program.title.replace(/[^a-z0-9]+/gi, "_").toLowerCase()}.png`;
    a.click();
  }

  return (
    <Modal open={!!program} onClose={onClose} title="Attendance Check-in QR">
      {program && (
        <div className="space-y-5 p-1 text-center">
          <div>
            <p className="text-sm font-semibold text-ink">{program.title}</p>
            <p className="mt-1 text-xs text-muted">
              Display this QR code at the venue. Approved volunteers scan it
              with their phone to check in — their attendance is recorded
              with a timestamp automatically.
            </p>
          </div>

          <div className="flex items-center justify-center rounded-card border border-sand-dark/40 bg-white p-6 min-h-[280px]">
            {loading ? (
              <RefreshCw size={28} className="animate-spin text-muted" />
            ) : dataUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={dataUrl} alt="Attendance check-in QR code" className="h-64 w-64" />
            ) : (
              <p className="text-xs text-muted">Could not generate QR code.</p>
            )}
          </div>

          <div className="rounded-card bg-sand/50 px-3 py-2 text-left">
            <p className="text-[10px] font-bold uppercase tracking-wider text-muted mb-1">
              Check-in link
            </p>
            <p className="break-all text-xs font-mono text-ink">{checkinUrl}</p>
          </div>

          <div className="flex justify-end gap-2">
            <Button variant="secondary" onClick={onClose}>
              Close
            </Button>
            <Button onClick={downloadQr} disabled={!dataUrl}>
              <Download size={14} /> Download QR
            </Button>
          </div>
        </div>
      )}
    </Modal>
  );
}
