"use client";
import { parseHoursInput } from "@/features/shared/clientReviewPolicy";

import { useCallback, useMemo, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import {
  markManualVolunteerAttendance,
  undoVolunteerAttendance,
  updateVolunteerAttendanceHours,
} from "@/features/opportunities/services/attendance";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";
import {
  AttendanceBearingRow,
  AttendanceRecordRef,
  ManualAttendanceResult,
  UntypedRow,
  atMidnight,
  readAttendanceRecord,
  effectiveAttendanceSelection,
  selectableAttendanceUuids,
  toApiDate,
  withCorrectedAttendance,
  withoutAttendance,
} from "../components/volunteerListHelpers";
import { useClock } from "@/hooks/useClock";

/** Share the live management clock so Kuwait midnight closes future-day selection. */
const ATTENDANCE_CLOCK_MS = 1000;

interface UseVolunteerAttendanceArgs {
  opportunityId: string | undefined;
  manual_tracking: boolean;
  opportunity_start_date: string | undefined;
  opportunity_end_date: string | undefined;
  /**
   * The session's end **time** (`HH:mm:ss`), not its end date.
   *
   * Needed at the hook level because the selection is derived here rather than
   * folded in page by page. It used to be threaded through each handler call
   * instead, which is how the auto-select path came to pass
   * `opportunity_end_date` where this value belongs — see the note on
   * `selectedAttendance`.
   */
  opportunity_end_time: string | undefined;
  allRegistrations: UntypedRow[];
  /**
   * Patch the merged rows in place, for the optimistic edit after marking
   * attendance. From `usePagedItems`, which owns the list — this used to be
   * the raw `setAllRegistrations` of a hand-rolled merge.
   */
  patchRegistrations: (updater: (rows: UntypedRow[]) => UntypedRow[]) => void;
}

/**
 * Everything to do with recording attendance for a session: which date is
 * selected, the manual check-in selection/bulk-mark flow, and inline hours
 * editing + undo. Registration data itself (fetching/pagination) stays owned
 * by the caller — this hook only reads and patches `allRegistrations`.
 */
export function useVolunteerAttendance({
  opportunityId,
  manual_tracking,
  opportunity_start_date,
  opportunity_end_date,
  opportunity_end_time,
  allRegistrations,
  patchRegistrations,
}: UseVolunteerAttendanceArgs) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  /**
   * The attendance date, defaulted from the opportunity's window.
   *
   * `null` means "nobody has picked one", in which case the default below
   * applies. Holding the override separately rather than seeding state from an
   * effect is what removes the post-paint write: the default is a *derivation*,
   * and only the organizer's pick is state.
   */
  const [dateOverride, setDateOverride] = useState<string | null>(null);
  /**
   * The rows the organizer ticked by hand. Only consulted when "select all" is
   * *not* in force — see `selectedAttendance` below.
   */
  const [explicitSelection, setExplicitSelection] = useState<string[]>([]);
  const [selectAllAttendance, setSelectAllAttendance] = useState(false);
  const [selectAllAttendanceMode, setSelectAllAttendanceMode] = useState(false);


  /**
   * Attendance records created or edited in this session, keyed
   * `<volunteer_uuid>|<YYYY-MM-DD>`. This is what makes the hours field and the
   * undo button usable today — the registrations payload does not yet carry
   * attendance ids (see `readAttendanceRecord`).
   */
  const [sessionAttendance, setSessionAttendance] = useState<
    Record<string, AttendanceRecordRef>
  >({});
  /** uuid|date currently being edited inline, and its draft value. */
  const [editingHoursKey, setEditingHoursKey] = useState<string | null>(null);
  const [hoursDraft, setHoursDraft] = useState("");
  /** Row awaiting undo confirmation. */
  const [pendingUndo, setPendingUndo] = useState<{
    attendanceId: string | number;
    key: string;
    volunteerName: string;
  } | null>(null);

  const markManualAttendanceMutation = useMutation({
    mutationFn: markManualVolunteerAttendance,
  });
  const updateAttendanceHoursMutation = useMutation({
    mutationFn: updateVolunteerAttendanceHours,
  });
  const undoAttendanceMutation = useMutation({
    mutationFn: undoVolunteerAttendance,
  });

  /*
   * Today when it falls inside the opportunity's window, otherwise the start
   * date — derived, not mirrored into state from an effect.
   *
   * "Today" comes from `useClock` rather than `new Date()` because this hook
   * runs in a Client Component that is still server-rendered: a bare
   * `new Date()` during render would be evaluated on both sides and could
   * disagree across midnight, which is a hydration mismatch. `useClock`'s
   * server snapshot is a fixed `0`, so the server renders the start date and the
   * browser's first real reading takes over without a `setState` after paint.
   *
   * The shared management clock also updates the selectable Kuwait day.
   */
  const clock = useClock(ATTENDANCE_CLOCK_MS);
  const defaultAttendanceDate = (() => {
    if (!opportunity_start_date) return "";

    const startDate = atMidnight(opportunity_start_date);
    const today = atMidnight(new Date(clock));

    if (!opportunity_end_date) return toApiDate(startDate.toISOString());

    const endDate = atMidnight(opportunity_end_date);
    if (today >= startDate && today <= endDate) return toApiDate(today.toISOString());
    // After the end the organizer is in the 72 h correction window: open on the last day, not
    // the first, so the «لم يسجل خروج» tags of a multi-day opportunity's final day are visible.
    return toApiDate((today > endDate ? endDate : startDate).toISOString());
  })();

  const selectedDate = dateOverride ?? defaultAttendanceDate;

  /**
   * The effective selection.
   *
   * **Derived while "select all" is in force**, rather than extended page by
   * page. `selectableAttendanceUuids` already answers "which of these rows may
   * be marked present", so with the mode on the answer for *every loaded row*
   * is the selection — there is nothing to accumulate. Unticking a row turns
   * the mode off (see `handleAttendanceCheckboxChange`), which is what makes
   * this sound.
   *
   * This replaces an `applySelectAllToNewPage(newRows)` callback that the
   * paging hook invoked for each merged page, reached through a ref assigned
   * in an effect so it would not be a render-time write. Deriving removes the
   * callback, the ref, the effect and two `set-state-in-effect` errors — and
   * one real defect with it: that callback passed `opportunity_end_date` as
   * the `opportunity_end_time` argument, so `canMarkAttendanceForDate` split
   * `"2026-10-05"` on `":"`, got `endHours = 2026` and `endMinutes = NaN`, and
   * returned false. A volunteer who registered **on the selected day** was
   * therefore left unselected when their page loaded, while the header toggle
   * — which passes the real end time — would have selected them. One code
   * path cannot disagree with itself.
   */
  const selectedAttendance = useMemo(
    () =>
      effectiveAttendanceSelection({
        selectAllMode: selectAllAttendanceMode,
        manualTracking: Boolean(manual_tracking),
        rows: allRegistrations,
        date: selectedDate,
        opportunity_start_date,
        opportunity_end_time,
        explicitSelection,
      }),
    [
      selectAllAttendanceMode,
      manual_tracking,
      allRegistrations,
      selectedDate,
      opportunity_start_date,
      opportunity_end_time,
      explicitSelection,
    ]
  );
  const setSelectedDate = setDateOverride;

  const effectiveEndDate = (() => {
    if (!opportunity_end_date) return "";
    // Attendance can only be recorded for today or earlier
    const today = atMidnight(new Date(clock));
    const endDate = atMidnight(opportunity_end_date);
    return today < endDate ? toApiDate(today.toISOString()) : opportunity_end_date;
  })();

  /*
   * Changing the date invalidates every pending selection — a tick entered for
   * Monday must not be submitted against Tuesday.
   *
   * Adjusted during render rather than from an effect: after paint, one frame
   * would show the previous day's ticks against the new date, and a fast
   * click in that frame would submit them.
   */
  const [clearedFor, setClearedFor] = useState(selectedDate);
  if (manual_tracking && clearedFor !== selectedDate) {
    setClearedFor(selectedDate);
    setExplicitSelection([]);
    setSelectAllAttendance(false);
    setSelectAllAttendanceMode(false);
  }

  const attendanceKey = (volunteerUuid: string, apiDate: string) =>
    `${volunteerUuid}|${apiDate}`;

  /** Session-recorded ids win — they are the freshest thing we know. */
  const resolveAttendanceRecord = useCallback(
    (
      row:
        | (AttendanceBearingRow & { volunteer_uuid?: string | null })
        | null
        | undefined,
      apiDate: string
    ): AttendanceRecordRef | null =>
      sessionAttendance[attendanceKey(row?.volunteer_uuid ?? "", apiDate)] ??
      readAttendanceRecord(row, apiDate),
    [sessionAttendance]
  );

  /*
   * Turning the header box on only raises the *mode* — the selection itself is
   * derived from it, so there is no list to build here and nothing to keep in
   * step as further pages arrive. Turning it off clears the explicit list,
   * which the derivation then falls back to.
   */
  const handleSelectAllAttendanceChange = () => {
    if (!manual_tracking) return;

    const newSelectAll = !selectAllAttendance;
    setSelectAllAttendance(newSelectAll);
    setSelectAllAttendanceMode(newSelectAll);
    if (!newSelectAll) setExplicitSelection([]);
  };

  const handleAttendanceCheckboxChange = (volunteerUuid: string) => {
    if (!manual_tracking) return;

    /*
     * `selectedAttendance` is the *derived* list while the mode is on, so an
     * untick has to commit it to `explicitSelection` as it leaves the mode —
     * otherwise the derivation would keep answering "everything" and the row
     * would tick itself straight back on.
     */
    let newSelectedAttendance: string[];
    if (selectedAttendance.includes(volunteerUuid)) {
      // Manually unchecking one item leaves "select all" mode
      newSelectedAttendance = selectedAttendance.filter(
        (id) => id !== volunteerUuid
      );
      setSelectAllAttendanceMode(false);
    } else {
      newSelectedAttendance = [...selectedAttendance, volunteerUuid];
    }
    setExplicitSelection(newSelectedAttendance);

    const formatted = toApiDate(selectedDate);
    const selectable = selectableAttendanceUuids(
      allRegistrations,
      selectedDate,
      opportunity_start_date,
      opportunity_end_time
    );
    const allSelected =
      selectable.length > 0 &&
      selectable.every((uuid) => {
        if (newSelectedAttendance.includes(uuid)) return true;
        const volunteer = allRegistrations.find(
          (row) => row.volunteer_uuid === uuid
        );
        return (volunteer?.date_wise_attended || []).includes(formatted);
      });

    setSelectAllAttendance(allSelected);
  };

  /**
   * Marks the selected volunteers present through the dedicated manual endpoint
   * (`POST /volunteer-attendance/manual/`), which runs alongside QR scanning
   * rather than replacing it. That endpoint takes one volunteer per call, so the
   * bulk selection fans out and the results are reported in aggregate; the hours
   * are left off so the backend derives them from the opportunity's duration.
   */
  const handleMarkAttendanceClick = async () => {
    if (!opportunityId || selectedAttendance.length === 0) {
      toast.error(t("COMMON.SELECT_USERS_TO_MARK"));
      return;
    }

    const attendanceDate = toApiDate(selectedDate);

    const results = await Promise.allSettled(
      selectedAttendance.map(
        (volunteerUuid): Promise<ManualAttendanceResult> =>
          markManualAttendanceMutation
            .mutateAsync({
              opportunity_id: opportunityId,
              volunteer_uuid: volunteerUuid,
              attendance_date: attendanceDate,
            })
            .then((response) => ({
              volunteerUuid,
              record: response?.data ?? null,
            }))
      )
    );

    const succeeded = results.filter(
      (result): result is PromiseFulfilledResult<ManualAttendanceResult> =>
        result.status === "fulfilled"
    );
    const failed = results.length - succeeded.length;

    if (succeeded.length > 0) {
      // Keep the returned attendance ids so hours and undo work immediately.
      setSessionAttendance((previous) => {
        const next = { ...previous };
        succeeded.forEach(({ value }) => {
          if (value.record?.id != null) {
            next[attendanceKey(value.volunteerUuid, attendanceDate)] = {
              id: value.record.id,
              total_hours: value.record.total_hours ?? null,
            };
          }
        });
        return next;
      });

      // Patch the rows in place rather than refetching — a reset here would
      // race the loader and blank the table.
      const attendedSet = new Set(succeeded.map(({ value }) => value.volunteerUuid));
      patchRegistrations((previous) =>
        previous.map((volunteer) => {
          /* A row with no `volunteer_uuid` cannot have been in the batch —
             the endpoint takes nothing else to identify by — so it is skipped
             before the lookup rather than probing the set with `null`. */
          if (
            !volunteer.volunteer_uuid ||
            !attendedSet.has(volunteer.volunteer_uuid)
          ) {
            return volunteer;
          }
          const existing: string[] = volunteer.date_wise_attended || [];
          if (existing.includes(attendanceDate)) return volunteer;
          return {
            ...volunteer,
            date_wise_attended: [...existing, attendanceDate],
          };
        })
      );

      toast.success(t("COMMON.USERS_MARKED_AS_ATTENDED"));
    }

    if (failed > 0) {
      const firstFailure = results.find(
        (result): result is PromiseRejectedResult => result.status === "rejected"
      );
      toast.error(
        getApiErrorMessage(
          firstFailure?.reason,
          selectedLanguage,
          t("COMMON.FAILED_TO_MARK_ATTENDED")
        )
      );
    }

    setExplicitSelection([]);
    setSelectAllAttendance(false);
    setSelectAllAttendanceMode(false);
  };

  /**
   * Inline hours correction — works on manual and QR records alike.
   *
   * `maxHours` is the most the day may carry — arrival → two hours past the
   * session's end (`maxCreditableHours`). Null when the schedule is unknown,
   * which falls back to the old 0–24 range rather than blocking the edit.
   */
  const handleSaveHours = async (
    attendanceId: string | number,
    key: string,
    rawValue: string,
    maxHours: number | null = null
  ) => {
    const hours = parseHoursInput(rawValue);
    if (!manual_tracking) return;
    const ceiling = 24;
    if (!rawValue.trim() || hours === null || hours < 0 || hours > ceiling) {
      toast.error(
        maxHours != null
          ? t("COMMON.ATTENDANCE_HOURS_MAX", { max: maxHours })
          : t("COMMON.ATTENDANCE_HOURS_RANGE")
      );
      return;
    }

    try {
      const response = await updateAttendanceHoursMutation.mutateAsync({
        attendance_id: attendanceId,
        total_hours: hours,
      });
      setSessionAttendance((previous) => ({
        ...previous,
        [key]: {
          ...previous[key],
          id: attendanceId,
          total_hours: response?.data?.total_hours ?? hours,
        },
      }));
      const saved = response?.data ?? {};
      patchRegistrations((previous) =>
        previous.map((row) =>
          withCorrectedAttendance(row, attendanceId, {
            total_hours: saved.total_hours ?? hours,
            total_minutes: saved.total_minutes,
            hours_set_manually_at: saved.hours_set_manually_at,
          })
        )
      );
      setEditingHoursKey(null);
      toast.success(t("COMMON.TOAST.ATTENDANCE_HOURS_SUCCESS"));
    } catch (error) {
      toast.error(
        getApiErrorMessage(
          error,
          selectedLanguage,
          t("COMMON.TOAST.ATTENDANCE_HOURS_FAILED")
        )
      );
    }
  };

  /**
   * Clears a check-in and returns the hours. The volunteer can then be marked
   * present again for the same day with corrected hours — that round trip is
   * the whole point of the endpoint.
   */
  const handleConfirmUndo = async () => {
    if (!manual_tracking) return;
    if (!pendingUndo) return;
    const { attendanceId, key } = pendingUndo;
    const [volunteerUuid, apiDate] = key.split("|");

    try {
      await undoAttendanceMutation.mutateAsync(attendanceId);

      setSessionAttendance((previous) => {
        const next = { ...previous };
        delete next[key];
        return next;
      });
      patchRegistrations((previous) =>
        previous.map((volunteer) =>
          volunteer.volunteer_uuid === volunteerUuid
            ? withoutAttendance(
                {
                  ...volunteer,
                  date_wise_attended: (volunteer.date_wise_attended || []).filter(
                    (date: string) => date !== apiDate
                  ),
                },
                attendanceId
              )
            : volunteer
        )
      );

      setPendingUndo(null);
      toast.success(t("COMMON.TOAST.ATTENDANCE_UNDO_SUCCESS"));
    } catch (error) {
      toast.error(
        getApiErrorMessage(
          error,
          selectedLanguage,
          t("COMMON.TOAST.ATTENDANCE_UNDO_FAILED")
        )
      );
    }
  };

  return {
    selectedDate,
    setSelectedDate,
    effectiveEndDate,
    selectedAttendance,
    selectAllAttendance,
    handleSelectAllAttendanceChange,
    handleAttendanceCheckboxChange,
    handleMarkAttendanceClick,
    isMarkingAttendance: markManualAttendanceMutation.isPending,
    editingHoursKey,
    setEditingHoursKey,
    hoursDraft,
    setHoursDraft,
    handleSaveHours,
    isSavingHours: updateAttendanceHoursMutation.isPending,
    pendingUndo,
    setPendingUndo,
    handleConfirmUndo,
    isUndoingAttendance: undoAttendanceMutation.isPending,
    resolveAttendanceRecord,
  };
}
