"use client";

import { useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import moment from "moment";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/Button";
import { getApiErrorMessage } from "@/lib/api/errors";
import { getVolunteerAttendanceCode } from "@/features/opportunities/services/selfCheckIn";
import { useLanguageStore } from "@/store/languageStore";
import AttendanceQrModal from "../AttendanceQrModal";
import { stashVolunteerListNavState } from "./volunteerListNavState";
import type { VolunteerOpportunityDetail } from "./types";
import { opportunityTitle, type VolunteerEventView } from "./volunteerEventView";

const LIST_BUTTON_CLASS =
  "!w-full max-w-[220px] px-5 text-sm font-bold !rounded-full";
const LIST_BUTTON_LABEL_CLASS =
  "whitespace-nowrap smallscreen1:text-sm";

function PanelButton({
  onClick,
  mobile = false,
  labelClassName = LIST_BUTTON_LABEL_CLASS,
  children,
}: {
  onClick: () => void;
  /** The mobile rows let each button take the full width on the narrowest screens. */
  mobile?: boolean;
  labelClassName?: string;
  children: ReactNode;
}) {
  return (
    <Button
      variant="primary"
      size="medium"
      onClick={onClick}
      className={
        mobile
          ? `${LIST_BUTTON_CLASS} smallscreen1:w-full smallscreen1:text-sm`
          : LIST_BUTTON_CLASS
      }
    >
      <span className={labelClassName}>{children}</span>
    </Button>
  );
}

interface AttendancePanelProps {
  data: VolunteerOpportunityDetail;
  view: Pick<
    VolunteerEventView,
    | "isCreator"
    | "checkInWindow"
    | "canManageAttendance"
    | "canGenerateAttendanceQr"
  >;
}

/**
 * The organizer's attendance controls — the volunteer list and the printed
 * attendance code (the same code for daily arrival and departure). Two layouts: one row on desktop / tablet, a stacked row on mobile.
 *
 * BE-61 Part C: the organizer-scans-the-volunteer's-QR flow is retired, so
 * neither the scanner nor the screen that delegated it appears here any more.
 * What replaces it is already on this page — the volunteer scans the printed
 * sheet themselves — with the manual roster behind «قائمة المتطوعين» as the
 * fallback the client asked to keep.
 */
export default function AttendancePanel({ data, view }: AttendancePanelProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const language = useLanguageStore((s) => s.language);
  const [showQr, setShowQr] = useState(false);

  const id = String(data.id);

  /**
   * BE-61 — the organizer's printable code. Fetched only once the dialog is
   * open: the call is idempotent but *creates* the code on first use, so
   * there is no reason to mint it for someone merely viewing the page.
   */
  const codeQuery = useQuery({
    queryKey: ["volunteer-attendance-code", id],
    queryFn: () => getVolunteerAttendanceCode(id),
    enabled: showQr,
    staleTime: Infinity,
  });

  const {
    isCreator,
    checkInWindow,
    canManageAttendance,
    canGenerateAttendanceQr,
  } = view;

  if (!canManageAttendance) return null;

  const goToVolunteerList = () => {
    stashVolunteerListNavState(data, checkInWindow, isCreator);
    router.push("/volunteerlist");
  };

  const title = opportunityTitle(data);
  const attendanceCode = codeQuery.data?.data;

  /* BE-100 — printed on the sheet, because the code expires: the last
     session's end plus the checkout grace, which can be days away, so the date
     is part of it. `is_expired` is the server's, not a comparison here — it
     owns the grace, and a sheet still on the wall should say it is dead rather
     than show a stale "valid until". */
  const qrFootnote = attendanceCode?.is_expired
    ? t("COMMON.QR_EXPIRED")
    : attendanceCode?.expires_at
      ? t("COMMON.QR_VALID_UNTIL", {
          date: moment(attendanceCode.expires_at).utcOffset(180).locale(language).format("DD MMM YYYY, hh:mm A"),
        })
      : undefined;

  return (
    <>
      <div
        className="w-full flex flex-col items-center pt-5"
      >
        <div className="flex w-full flex-col items-center gap-3">
          <PanelButton onClick={goToVolunteerList}>
            {t("COMMON.LIST_OF_VOLUNTEERS")}
          </PanelButton>
          {canGenerateAttendanceQr && (
            <PanelButton onClick={() => setShowQr(true)}>
              {t("COMMON.ATTENDANCE_QR")}
            </PanelButton>
          )}
        </div>

      </div>

      {/* BE-61 — the organizer's one printed sheet. */}
      <AttendanceQrModal
        open={showQr}
        onClose={() => setShowQr(false)}
        title={t("COMMON.ATTENDANCE_QR")}
        instructions={t("COMMON.ATTENDANCE_QR_INSTRUCTIONS")}
        isLoading={codeQuery.isLoading}
        error={
          codeQuery.isError
            ? getApiErrorMessage(codeQuery.error, language) ||
              t("COMMON.TOAST.ATTENDANCE_QR_FAILED")
            : null
        }
        sheets={
          attendanceCode?.code
            ? [
                {
                  code: attendanceCode.code,
                  label: t("COMMON.ATTENDANCE_QR"),
                  caption: title,
                  footnote: qrFootnote,
                },
              ]
            : []
        }
      />
    </>
  );
}
