"use client";

import UndoDevelopmentAttendance from "./UndoDevelopmentAttendance";
import Image from "next/image";
import { useTranslation } from "react-i18next";
import { RiDeleteBin5Fill } from "react-icons/ri";
import type { TableColumn } from "@/components/ui/Table";
import { getDefaultProfileImage } from "@/lib/helpers";
import { registrationPerson } from "@/features/opportunities/registrationRow";
import RegistrationEmergencyCell from "./RegistrationEmergencyCell";
import { type RegisteredUser } from "./learnServeRegisterListTypes";
import ProfileLink from "@/components/shared/ProfileLink";

const asset = (path: string) => `/assets/${path}`;

interface RegistrationRowCellsProps {
  column: TableColumn;
  rowData: RegisteredUser;
  selectedLanguage: string;
  selectedUsers: string[];
  onToggle: (userId: string | number) => void;
  /** Delete stays visible past the deadline, but disabled — not hidden. */
  isAfterAttendanceDeadline: boolean;
  canMarkAttendance?: boolean;
  opportunityId?: string;
  onAttendanceUndone?: () => void;
  /**
   * Why this row may not be removed, if anything besides the deadline — on a
   * paid opportunity, a participant who paid or is paying (`paidRemovalBlock`).
   * The bin stays, disabled, with the answer as its tooltip.
   */
  deleteBlockedLabelFor?: (row: RegisteredUser) => string | null;
  onDelete: (userId: string | number, userName: string) => void;
  /** Drives only the bin icon's size; the row is otherwise CSS-responsive. */
  windowWidth: number;
}

/** One cell of the registrations table, dispatched on the column's type. */
export default function RegistrationRowCells({
  column,
  rowData,
  selectedLanguage,
  selectedUsers,
  onToggle,
  isAfterAttendanceDeadline,
  canMarkAttendance = false,
  opportunityId, onAttendanceUndone,
  deleteBlockedLabelFor,
  onDelete,
  windowWidth,
}: RegistrationRowCellsProps) {
  const { t } = useTranslation();

  const person = registrationPerson(rowData);
  const defaultProfilePic = getDefaultProfileImage(
    person.genderEn || "unknown",
    asset("profile/male_profile.svg"),
    asset("profile/female_profile.svg"),
    asset("profile/org_profile.svg")
  );

  if (column.type === "attendance") {
    const checked =
      rowData.is_attended || selectedUsers.includes(rowData.id.toString());
    return (
      <div className="flex flex-col items-center justify-center gap-2">
        <div className="relative border p-1 border-secondary-100">
          <div className={`h-4 w-4 ${checked ? "bg-[#373737BF]/75" : "bg-white"}`}>
            <input
              type="checkbox"
              checked={checked}
              onChange={() => !rowData.is_attended && onToggle(rowData.id)}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
              /* `?? undefined`: `is_attended` is nullable on the learn &
                 serve resource, and `disabled` takes `boolean | undefined` —
                 null would be passed straight to the DOM attribute. */
              disabled={!canMarkAttendance || Boolean(rowData.is_attended)}
              aria-label={t("COMMON.MARK_ATTENDANCE_FOR", { name: person.name ?? "" })}
            />
          </div>
        </div>
        {rowData.is_attended && opportunityId && <UndoDevelopmentAttendance opportunityId={opportunityId} registrationId={Number(rowData.id)} disabled={!canMarkAttendance} onUndone={() => onAttendanceUndone?.()} />}
      </div>
    );
  }

  if (column.type === "custom" && column.key === "full_name") {
    const userId = person.userId || rowData.id;
    return (
      <div className="flex items-center gap-3">
        <Image
          src={person.profilePic || defaultProfilePic}
          alt={person.name}
          width={40}
          height={40}
          unoptimized
          className="h-10 w-10 rounded-full object-cover"
        />
        <div className="flex flex-col">
          <ProfileLink
            id={userId}
            className="cursor-pointer text-primary-5"
          >
            {person.name || "-"}
          </ProfileLink>
          {/* Reports show the volunteer's civil ID under the name */}
          {person.civilId && (
            <span className="text-xs text-gray-500">{person.civilId}</span>
          )}
        </div>
      </div>
    );
  }

  if (column.type === "email") return <span>{person.email || "-"}</span>;
  if (column.type === "contact") return <bdi dir="ltr" className="inline-block whitespace-nowrap">{person.phone || "-"}</bdi>;

  if (column.type === "emergency") {
    return (
      <RegistrationEmergencyCell
        columnKey={column.key}
        rowData={rowData}
        selectedLanguage={selectedLanguage}
      />
    );
  }

  if (column.type === "actions") {
    const localizedName =
      selectedLanguage === "ar" ? person.nameAr : person.name;
    const deleteBlockedLabel = deleteBlockedLabelFor?.(rowData) ?? null;
    const deleteDisabled = isAfterAttendanceDeadline || rowData.can_exclude === false || Boolean(deleteBlockedLabel);
    const deleteLabel = deleteBlockedLabel || t("COMMON.DELETE_REGISTRATION");

    return (
      <div
        className={`flex ${
          selectedLanguage === "ar"
            ? "mr-[10px] mobilescreen:mr-[5px]"
            : "ml-[18px] mobilescreen:ml-[14px]"
        }`}
      >
        <button
          onClick={() =>
            !deleteDisabled &&
            person.userId &&
            onDelete(person.userId, localizedName)
          }
          className={`text-primary-5 flex items-center gap-2 ${
            deleteDisabled
              ? "opacity-50 cursor-not-allowed"
              : "cursor-pointer"
          }`}
          title={deleteLabel}
          aria-label={deleteLabel}
          disabled={deleteDisabled}
        >
          <RiDeleteBin5Fill size={windowWidth <= 767 ? 18 : 24} />
        </button>
      </div>
    );
  }

  return <span>{(rowData as unknown as Record<string, string>)[column.key] || "-"}</span>;
}
