"use client";

import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import AttendanceQrSheet from "./AttendanceQrSheet";

export interface AttendanceQrSheetData {
  code: string;
  label: string;
  caption?: string;
  footnote?: string;
}

interface AttendanceQrModalProps {
  open: boolean;
  onClose: () => void;
  title: string;
  /** One sheet — both volunteering and learn & serve print a single code. */
  sheets: AttendanceQrSheetData[];
  isLoading?: boolean;
  /** Already-localized failure text from the API, shown in place of the sheets. */
  error?: string | null;
  /** Shown above the sheets — how this particular code is meant to be used. */
  instructions?: string;
}

/**
 * The organizer's view of the attendance codes, built to be printed from.
 *
 * Printing goes through the browser rather than a generated PDF: the sheets are
 * already SVG, `@media print` in `globals.css` hides everything else on the
 * page, and each sheet breaks onto its own page.
 */
export default function AttendanceQrModal({
  open,
  onClose,
  title,
  sheets,
  isLoading = false,
  error = null,
  instructions,
}: AttendanceQrModalProps) {
  const { t } = useTranslation();
  // The print copy is a portal under <body>. The modal only opens after a
  // click, so it is never open during the server render or hydration.
  const printable =
    open && !isLoading && !error && sheets.length > 0 && typeof document !== "undefined";

  return (
    <>
    {/* What the printer sees: the sheets alone, one per page, outside the
        modal's clipped panel. Hidden on screen by `.qr-print-root`. */}
    {printable
      ? createPortal(
          <div className="qr-print-root" dir={document.documentElement.dir || undefined}>
            {sheets.map((sheet) => (
              <AttendanceQrSheet key={sheet.code} {...sheet} />
            ))}
          </div>,
          document.body
        )
      : null}
    <Modal open={open} onClose={onClose} title={title} size="md" className="attendance-qr-dialog">
      <div className="flex flex-col gap-3">
        {isLoading ? (
          <Loader />
        ) : error ? (
          <p className="qr-print-hide text-center text-base font-semibold text-red-500">
            {error}
          </p>
        ) : (
          <>
            {instructions ? (
              <p className="qr-print-hide text-center text-sm leading-relaxed font-semibold text-secondary-102">
                {instructions}
              </p>
            ) : null}

            <div className="flex flex-wrap justify-center gap-3">
              {sheets.map((sheet) => (
                <AttendanceQrSheet key={sheet.code} {...sheet} />
              ))}
            </div>
          </>
        )}

        <div className="qr-print-hide flex flex-wrap justify-center gap-3">
          {!isLoading && !error && sheets.length > 0 && (
            <Button
              variant="primary"
              size="medium"
              type="button"
              className="xss:!w-full"
              onClick={() => window.print()}
            >
              {t("COMMON.PRINT")}
            </Button>
          )}
          <Button
            variant="secondary"
            size="medium"
            type="button"
            className="xss:!w-full"
            onClick={onClose}
          >
            {t("COMMON.CLOSE")}
          </Button>
        </div>
      </div>
    </Modal>
    </>
  );
}
