"use client";

import { useTranslation } from "react-i18next";
import { IoInformationCircleOutline } from "react-icons/io5";

import {
  paymentStatusClass,
  paymentStatusKey,
} from "@/features/opportunities/paymentStatusLabel";
import type { ParticipantPaymentRow } from "@/features/opportunities/participantPaymentRecord";
import {
  registrationPerson,
  type RegistrationRow,
} from "@/features/opportunities/registrationRow";
import RegistrationNameCell from "./RegistrationNameCell";

interface ParticipantsPaymentsTableProps {
  rows: ParticipantPaymentRow[];
  /** Registrations keyed by id — the phone, photo and civil ID. */
  people: Map<string, RegistrationRow>;
  feePercent: number | null;
  refundingIds: Set<number>;
  /** While «refund all» runs every row button stays put. */
  refundingAll: boolean;
}

const toNumber = (value: number | string | null | undefined): number | null => {
  if (value === null || value === undefined || value === "") return null;
  const n = Number(value);
  return Number.isFinite(n) ? n : null;
};

/**
 * What the platform kept from one payment: its commission plus whatever the
 * gateway charged. Null when neither is known — a dash, not a zero, since
 * `0.000` would read as "nothing was taken".
 */
export function rowDeductions(row: ParticipantPaymentRow): number | null {
  const platform = toNumber(row.platform_fee_amount);
  return platform;
}

/**
 * BE-125 — «المشاركون والمدفوعات», laid out after the client's design: the
 * participant (photo, name, civil ID), contact, payment status, the amount
 * paid, the deductions with what they consist of and the net, closed by a
 * totals row. No refund per row: a publisher never refunds one participant
 * (PDF p.18); refunds go through the administration or «طلب استرجاع الكل».
 *
 * The totals count **paid** rows only: a refunded payment was returned, and a
 * pending or failed one never arrived, so neither belongs in what the
 * organizer is owed. Amounts are KWD to three decimals (fils), as designed.
 */
export default function ParticipantsPaymentsTable({
  rows,
  people,
  feePercent,
}: ParticipantsPaymentsTableProps) {
  const { t } = useTranslation();

  const kwd = (value: number | null) =>
    value === null ? "-" : `${value.toFixed(3)} ${t("COMMON.KWD_SHORT")}`;

  const paidRows = rows.filter((row) => row.payment_status === "paid");
  const sum = (pick: (row: ParticipantPaymentRow) => number | null) => {
    const values = paidRows.map(pick).filter((v): v is number => v !== null);
    return values.length ? values.reduce((a, b) => a + b, 0) : null;
  };
  const totalGross = sum((row) => toNumber(row.gross_amount));
  const totalDeductions = sum(rowDeductions);
  const totalNet = sum((row) => toNumber(row.net_amount));

  const th = "px-3 py-3 text-start text-sm font-bold text-primary-5 whitespace-nowrap";
  const td = "px-3 py-3 text-sm text-primary-5 whitespace-nowrap";

  return (
    <div className="w-full overflow-x-auto">
      <table className="w-full min-w-[960px] border-collapse">
        <thead>
          <tr className="border-b border-[#29246D1A]">
            <th className={th}>{t("COMMON.NAME")}</th>
            <th className={th}>{t("COMMON.EMAIL")}</th>
            <th className={th}>{t("COMMON.PAYMENTS_COL_PHONE")}</th>
            <th className={th}>{t("COMMON.PAYMENT_STATUS")}</th>
            <th className={th}>{t("COMMON.AMOUNT_PAID")}</th>
            <th className={th}>
              <span className="inline-flex items-center gap-1">
                {t("COMMON.DEDUCTIONS")}
                <IoInformationCircleOutline
                  size={16}
                  aria-label={feePercent === null ? t("COMMON.DEDUCTIONS") : t("COMMON.DEDUCTIONS_HINT", { percent: feePercent })}
                />
              </span>
              {feePercent !== null && <span className="block text-[11px] font-normal text-secondary-102">
                {t("COMMON.DEDUCTIONS_HINT", { percent: feePercent })}
              </span>}
            </th>
            <th className={th}>{t("COMMON.NET_AMOUNT")}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => {
            const registration = people.get(String(row.registration_id));
            const person = registrationPerson(registration);

            return (
              <tr key={row.id} className="border-b border-[#29246D0F]">
                <td className={td}>
                  <RegistrationNameCell
                    rowData={
                      registration ?? {
                        id: row.registration_id,
                        user_id: row.user_id,
                        user_name: row.user_name,
                      }
                    }
                  />
                </td>
                <td className={td}>{row.user_email || person.email || "-"}</td>
                <td className={td} dir="ltr">
                  {person.phone || "-"}
                </td>
                <td className={td}>
                  <span
                    className={`rounded-full px-3 py-1 text-xs font-bold ${paymentStatusClass(
                      row.payment_status
                    )}`}
                  >
                    {t(paymentStatusKey(row.payment_status))}
                  </span>
                </td>
                <td className={td}>{kwd(toNumber(row.gross_amount))}</td>
                <td className={td}>{kwd(rowDeductions(row))}</td>
                <td className={td}>{kwd(toNumber(row.net_amount))}</td>

              </tr>
            );
          })}
        </tbody>
        <tfoot>
          <tr className="bg-[#F3F4F9]">
            <td className={`${td} font-bold`} colSpan={4}>
              {t("COMMON.TOTAL")}
            </td>
            <td className={`${td} font-bold`}>{kwd(totalGross)}</td>
            <td className={`${td} font-bold`}>{kwd(totalDeductions)}</td>
            <td className={`${td} font-bold`}>{kwd(totalNet)}</td>
          </tr>
        </tfoot>
      </table>
    </div>
  );
}
