"use client";

import { useTranslation } from "react-i18next";
import { TableColumn } from "@/components/ui/Table";
import { shouldShowEmergencyContact } from "@/features/opportunities/registrationEmergencyContact";
import AttendanceHoursCell from "./AttendanceHoursCell";
import AttendanceCheckboxCell from "./AttendanceCheckboxCell";
import RegistrationNameCell from "./RegistrationNameCell";
import RegistrationActionsCell from "./RegistrationActionsCell";
import RegistrationSelectCell from "./RegistrationSelectCell";
import { missedCheckOutDays, toApiDate, type UntypedRow } from "./volunteerListHelpers";
import { VolunteerRegistrationsTableProps } from "./VolunteerRegistrationsTable";

/**
 * Derived from the table's own props rather than restated, so a signature change
 * there is a compile error here instead of a silent mismatch. Only the three
 * that are per-cell are declared.
 */
type VolunteerRegistrationCellProps = Pick<
  VolunteerRegistrationsTableProps,
  | "selectedDate"
  | "manual_tracking"
  | "opportunity_start_date"
  | "opportunity_end_time"
  | "schedule"
  | "exclusionSource"
  | "roleDisabled"
  | "selectedAttendance"
  | "onAttendanceCheckboxChange"
  | "roleOptions"
  | "rolesLoading"
  | "updatingId"
  | "updating"
  | "onUpdate"
  | "onRoleMenuScroll"
  | "editingHoursKey"
  | "setEditingHoursKey"
  | "hoursDraft"
  | "setHoursDraft"
  | "onSaveHours"
  | "isSavingHours"
  | "resolveAttendanceRecord"
  | "onRequestUndo"
  | "onRequestUnregister"
> & {
  column: TableColumn;
  rowData: UntypedRow;
  selectedLanguage: string;
};

/**
 * One cell of the volunteering registrations table.
 *
 * The attendance checkbox is where most of the rules live: it is disabled when
 * the volunteer is already marked for the selected date, when manual tracking is
 * shut, when that date is not one of *their* days, and when the day's session
 * has not reached the point where attendance can be recorded. All four are
 * separate reasons and all four render the same disabled state.
 */
export default function VolunteerRegistrationCell({
  column,
  rowData,
  selectedLanguage,
  selectedDate,
  manual_tracking,
  opportunity_start_date,
  opportunity_end_time,
  schedule,
  exclusionSource,
  roleDisabled,
  selectedAttendance,
  onAttendanceCheckboxChange,
  roleOptions,
  rolesLoading,
  updatingId,
  updating,
  onUpdate,
  onRoleMenuScroll,
  editingHoursKey,
  setEditingHoursKey,
  hoursDraft,
  setHoursDraft,
  onSaveHours,
  isSavingHours,
  resolveAttendanceRecord,
  onRequestUndo,
  onRequestUnregister,
}: VolunteerRegistrationCellProps) {
  const { t } = useTranslation();


  if (column.type === "custom" && column.key === "full_name") {
    return (
      <RegistrationNameCell
        rowData={rowData}
        missedCheckOut={missedCheckOutDays(rowData).includes(toApiDate(selectedDate))}
      />
    );
  }

  if (column.type === "role") {
    return (
      <RegistrationSelectCell
        options={roleOptions}
        value={String(rowData.role?.id || "")}
        /* `String(...)`: the id is a number on the row and
           `updateVolunteerRegistration` sends `registration` as a string. */
        onChange={(value) => onUpdate(String(rowData.id), "role", value)}
        onMenuScrollToBottom={onRoleMenuScroll}
        isLoading={rolesLoading}
        isDisabled={
  roleDisabled || rolesLoading ||
  /* Compared as strings. `updatingId` is `string | null` and `rowData.id`
     is a number, so `===` was **always false** and the role dropdown never
     showed its own in-flight state — it stayed enabled through the PATCH.
     Surfaced by typing the row. */
  (updatingId === String(rowData.id) && updating === "role")
        }
        placeholder={t("COMMON.ROLE")}
      />
    );
  }

  if (column.type === "attendance") {
    return (
      <AttendanceCheckboxCell
        rowData={rowData}
        selectedDate={selectedDate}
        manual_tracking={manual_tracking}
        opportunity_start_date={opportunity_start_date}
        opportunity_end_time={opportunity_end_time}
        selectedAttendance={selectedAttendance}
        onAttendanceCheckboxChange={onAttendanceCheckboxChange}
      />
    );
  }

  if (column.type === "attendance_hours") {
    return (
      <AttendanceHoursCell
        editable={manual_tracking}
        rowData={rowData}
        selectedDate={selectedDate}
        schedule={schedule}
        editingHoursKey={editingHoursKey}
        setEditingHoursKey={setEditingHoursKey}
        hoursDraft={hoursDraft}
        setHoursDraft={setHoursDraft}
        onSaveHours={onSaveHours}
        isSavingHours={isSavingHours}
        resolveAttendanceRecord={resolveAttendanceRecord}
        onRequestUndo={onRequestUndo}
      />
    );
  }

  if (column.key === "phone_number" || column.key === "user_contact_number") {
    const fields = rowData as unknown as Record<string, unknown>;
    return <bdi dir="ltr" className="inline-block whitespace-nowrap">{String(fields[column.key] ?? "") || "-"}</bdi>;
  }

  if (column.type === "emergency") {
    if (!shouldShowEmergencyContact(rowData)) {
      return <span>-</span>;
    }

    if (column.key === "emergency_contact_relationship") {
      const relationship =
        rowData?.user?.emergency_contact_relationship_display;
      return (
        <span>
  {relationship
    ? selectedLanguage === "ar"
      ? relationship.value_ar
      : relationship.value_en
    : "-"}
        </span>
      );
    }

    /* The column keys are configured elsewhere, so the lookup is dynamic.
       Indexed through a record view rather than `any`: this says "some string
       key of the user block", which is what a configured column is, and it
       keeps the *row* type intact for every other branch above. */
    const userFields = rowData?.user as Record<string, unknown> | null | undefined;
    if (column.key === "emergency_contact_phone") {
      return <bdi dir="ltr" className="inline-block whitespace-nowrap">{String(userFields?.[column.key] ?? "") || "-"}</bdi>;
    }
    return <span>{String(userFields?.[column.key] ?? "") || "-"}</span>;
  }

  if (column.type === "actions") {
    return (
      <RegistrationActionsCell
        rowData={rowData}
        selectedLanguage={selectedLanguage}
        exclusionSource={exclusionSource}
        onRequestUnregister={onRequestUnregister}
      />
    );
  }

  /* Same dynamic-column read, on the row itself. */
  const rowFields = rowData as unknown as Record<string, unknown>;
  return <span>{String(rowFields[column.key] ?? "") || "-"}</span>;

}
