"use client";

import { formatHoursMinutes, parseHoursInput } from "@/features/shared/clientReviewPolicy";
import { useTranslation } from "react-i18next";
import { FaCheck, FaPen, FaRotateLeft } from "react-icons/fa6";
import { RxCross1 } from "react-icons/rx";
import {
  type AttendanceScheduleSource,
  attendanceHoursState,
  sessionOnDate,
  splitHours,
} from "../attendanceHours";
import { AttendanceRecordRef, UntypedRow, toApiDate } from "./volunteerListHelpers";

interface AttendanceHoursCellProps {
  editable?: boolean;
  rowData: UntypedRow;
  selectedDate: string;
  schedule: AttendanceScheduleSource;
  editingHoursKey: string | null;
  setEditingHoursKey: (key: string | null) => void;
  hoursDraft: string;
  setHoursDraft: (value: string) => void;
  onSaveHours: (
    attendanceId: string | number,
    key: string,
    rawValue: string,
    maxHours?: number | null
  ) => Promise<void>;
  isSavingHours: boolean;
  resolveAttendanceRecord: (
    row: UntypedRow,
    apiDate: string
  ) => AttendanceRecordRef | null;
  onRequestUndo: (payload: {
    attendanceId: string | number;
    key: string;
    volunteerName: string;
  }) => void;
}

/** Actual daily hours, editable manually up to 24 hours during preparation. */
export default function AttendanceHoursCell({
  editable = true,
  rowData,
  selectedDate,
  schedule,
  editingHoursKey,
  setEditingHoursKey,
  hoursDraft,
  setHoursDraft,
  onSaveHours,
  isSavingHours,
  resolveAttendanceRecord,
  onRequestUndo,
}: AttendanceHoursCellProps) {
  const { t } = useTranslation();

  const apiDate = toApiDate(selectedDate);
  const isAttended = (rowData.date_wise_attended || []).includes(apiDate);

  if (!isAttended) {
    return <span className="text-gray-400">-</span>;
  }

  const record = resolveAttendanceRecord(rowData, apiDate);
  const key = `${rowData.volunteer_uuid}|${apiDate}`;

  // No id means no way to address the record — show the hours read-only.
  // BE-67.2 makes this the rare case rather than the norm: `attendances[]` now
  // carries the id for every attended date, so this only trips on a row whose
  // check-in the list has not refetched yet.
  if (!record) {
    /* `"-"`, with no `rowData.total_hours` fallback: the registrations
       resource has no flat `total_hours` — the hours live on
       `attendances[].total_hours`, which is where `readAttendanceRecord`
       looks. The old operand was always `undefined`, and `"-"` is the right
       answer anyway: no record means no hours for this date. */
    return <span className="text-secondary-102">-</span>;
  }

  // One helper, so the "what state is this row in" rules sit with the hours
  // arithmetic and can be tested without a render. The server's `max_hours`
  // wins where BE-91 sends it.
  const session = sessionOnDate(schedule, apiDate);
  const { maxHours } = attendanceHoursState(record, session);

  const draftValue = parseHoursInput(hoursDraft);
  const draftDuration =
    hoursDraft.trim() && draftValue !== null && draftValue >= 0
      ? splitHours(draftValue)
      : null;

  if (!editable) return <span dir="ltr">{formatHoursMinutes(record.total_hours)}</span>;

  if (editingHoursKey === key) {
    // Enter bypasses the disabled button, so the pending check lives here too.
    const save = () => { if (!isSavingHours) void onSaveHours(record.id, key, hoursDraft, maxHours); };
    return (
      <div className="flex flex-col items-center gap-1">
        <div className="flex items-center gap-1 justify-center">
          <input
            type="text"
            inputMode="numeric"
            placeholder="H:MM"
            dir="ltr"
            value={hoursDraft}
            autoFocus
            onChange={(event) => setHoursDraft(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === "Enter") save();
              if (event.key === "Escape") setEditingHoursKey(null);
            }}
            className="w-16 border border-primary-5 rounded px-1 py-0.5 text-center"
            aria-label={t("COMMON.ATTENDANCE_HOURS")}
          />
          <button
            type="button"
            onClick={save}
            disabled={isSavingHours}
            className="text-primary-5 disabled:opacity-50"
            aria-label={t("COMMON.SAVE")}
          >
            <FaCheck size={14} />
          </button>
          <button
            type="button"
            onClick={() => setEditingHoursKey(null)}
            className="text-secondary-102"
            aria-label={t("COMMON.CANCEL")}
          >
            <RxCross1 size={14} />
          </button>
        </div>
        <span className="text-xs text-gray-500 whitespace-nowrap">
          {draftDuration && t("COMMON.DURATION_HOURS_MINUTES", draftDuration)}
          {draftDuration && maxHours != null && " · "}
          {maxHours != null &&
            t("COMMON.ATTENDANCE_HOURS_MAX_HINT", { max: maxHours })}
        </span>
      </div>
    );
  }

  return (
    <div className="flex items-center gap-2 justify-center">
      <span className="text-secondary-102">
        {/* No `rowData.total_hours` operand — see the branch above. */}
        {record.total_hours != null ? formatHoursMinutes(record.total_hours) : "-"}
      </span>
      <button
        type="button"
        onClick={() => {
          setEditingHoursKey(key);
          setHoursDraft(
            record.total_hours != null ? formatHoursMinutes(record.total_hours) : ""
          );
        }}
        className="text-primary-5 hover:text-primary-5/80"
        title={t("COMMON.EDIT_HOURS")}
        aria-label={t("COMMON.EDIT_HOURS")}
      >
        <FaPen size={12} />
      </button>
      <button
        type="button"
        onClick={() =>
          onRequestUndo({
            attendanceId: record.id,
            key,
            /* `full_name` only: `user_full_name` was the other operand and
               appears nowhere in the backend. */
            volunteerName: rowData.full_name || "",
          })
        }
        className="text-[#D32F2F] hover:text-[#D32F2F]/80"
        title={t("COMMON.UNDO_ATTENDANCE")}
        aria-label={t("COMMON.UNDO_ATTENDANCE")}
      >
        <FaRotateLeft size={12} />
      </button>
    </div>
  );
}
