"use client";

import moment from "moment";
import { CircleCheck, CalendarCheck, ScanLine } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/Button";
import { ATTENDANCE_LOCATION_RADIUS_M } from "@/features/opportunities/attendanceLocation";
import { useLanguageStore } from "@/store/languageStore";
import SelfScanModal from "../SelfScanModal";
import { useVolunteerSelfScan } from "./useVolunteerSelfScan";
import { VolunteerOpportunityDetail } from "./types";

interface SelfScanPanelProps {
  data: VolunteerOpportunityDetail;
  isCreator: boolean;
  /** Called after a scan lands, so the page re-reads `self_attendance`. */
  onRecorded: () => void;
}

/**
 * The participant scans the same printed code on daily arrival and departure.
 * The API exposes the next action and records actual minutes between scans.
 *
 * Deliberately separate from the attendance-management block, which is gated
 * on being the creator or a delegated scanner; this one belongs to the
 * participant. `self_attendance` is null unless the backend sees the viewer as
 * registered, so it doubles as the registration check.
 *
 * The scan window (one hour before the session to its end + grace) is the
 * server's to enforce: a scan outside it is a 400 whose message is shown as
 * sent, rather than a client-side clock guess hiding the button.
 */
export default function SelfScanPanel({
  data,
  isCreator,
  onRecorded,
}: SelfScanPanelProps) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);

  const selfAttendance = data.self_attendance;
  const attendedToday = Boolean(selfAttendance?.attended_today);
  const nextAction = selfAttendance?.next_action;
  const attendedCount = Number(selfAttendance?.attended_count ?? 0);
  const scannedAt = selfAttendance?.scanned_at
    ? moment(selfAttendance.scanned_at).utcOffset(180).locale(language)
    : null;
  const scannedAtLabel = scannedAt?.isValid() ? scannedAt.format("hh:mm A") : "";

  const canScan = !isCreator && Boolean(selfAttendance) && (selfAttendance?.can_scan ?? (nextAction != null || !attendedToday));

  const scan = useVolunteerSelfScan({ data, language, t, onRecorded });

  // After the hooks, never before: an early return above them would change the
  // hook order between renders.
  if (isCreator || !selfAttendance) return null;

  return (
    <>
      <div className="mt-5 flex w-full min-w-0 flex-col items-stretch gap-3 border-t border-primary-5/10 pt-4">
        {canScan && (
          <Button
            variant="primary"
            size="medium"
            onClick={scan.openScanner}
            loading={scan.locating}
            disabled={scan.locating}
            className="!w-full min-w-0 gap-2 !rounded-full !px-3 text-sm"
          >
            <ScanLine className="h-4 w-4 shrink-0" aria-hidden="true" />
            <span className="whitespace-normal leading-snug">{t(nextAction === "check_out" ? "COMMON.SCAN_DEPARTURE_QR" : "COMMON.SCAN_ATTENDANCE_QR")}</span>
          </Button>
        )}

        {canScan && scan.needsLocation && (
          <p className="text-center text-xs leading-relaxed text-secondary-102">
            {t("COMMON.ATTENDANCE_LOCATION_HINT", {
              meters: ATTENDANCE_LOCATION_RADIUS_M,
            })}
          </p>
        )}

        {attendedToday && (
          <div role="status" className="flex items-start gap-2 rounded-xl bg-emerald-50 px-3 py-3 text-start text-sm font-medium leading-relaxed text-emerald-800">
            <CircleCheck className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
            <p className="min-w-0 break-words">{scannedAtLabel
              ? t("COMMON.ATTENDED_TODAY_AT", { time: scannedAtLabel })
              : t("COMMON.ATTENDED_TODAY")}</p>
          </div>
        )}

        {attendedCount > 0 && (
          <div className="flex items-center justify-center gap-2 text-xs leading-relaxed text-secondary-102">
            <CalendarCheck className="h-4 w-4 shrink-0 text-primary-5/60" aria-hidden="true" />
            <p>{t("COMMON.ATTENDED_DAYS_COUNT", { count: attendedCount })}</p>
          </div>
        )}
      </div>

      <SelfScanModal
        open={scan.open}
        onClose={() => scan.setOpen(false)}
        title={t(nextAction === "check_out" ? "COMMON.SCAN_DEPARTURE_QR" : "COMMON.SCAN_ATTENDANCE_QR")}
        hint={t("COMMON.VOLUNTEER_DAILY_SCAN_HINT")}
        onScan={scan.handleScan}
        isPending={scan.isPending || scan.locating}
      />
    </>
  );
}
