"use client";

import { useMemo, useState } from "react";
import moment from "moment";
import { useTranslation } from "react-i18next";
import { FiRefreshCw } from "react-icons/fi";

import Button from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import Searchbar from "@/components/ui/Searchbar";
import PaidCancellationRequest from "./PaidCancellationRequest";
import PaymentsFilterModal from "./PaymentsFilterModal";
import ParticipantsPaymentsTable from "./ParticipantsPaymentsTable";
import { useParticipantsPayments } from "./useParticipantsPayments";
import { registrationPerson } from "@/features/opportunities/registrationRow";
import { canOpenRefundAll } from "@/features/opportunities/participantPaymentRecord";
import type { ReviewSchedule } from "@/features/shared/clientReviewPolicy";
import { useClock } from "@/hooks/useClock";

/** `YYYY-MM-DD` of an ISO timestamp, in the viewer's own day. */
const localDay = (iso: string | null) => {
  if (!iso) return "";
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return "";
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
};

/**
 * BE-125 — «المشاركون والمدفوعات» for one paid development opportunity, after
 * the client's design (2026-10-10).
 *
 * A section of the registrations screen (client, 2026-10-15) — it used to be
 * its own page, `/learn-share-payments`, opened by a button there. The
 * registrations screen renders it for a paid opportunity and passes the id.
 *
 * Search and the date filter run over the rows already loaded — the hook
 * loads all of them, and the endpoint takes neither parameter (BE-123). The
 * date is the payment date.
 */
export default function ParticipantsPayments({
  opportunityId,
  schedule,
  onRefunded,
}: {
  opportunityId: string;
  /** The course's schedule and status, from the registrations screen's payload. */
  schedule?: ReviewSchedule | null;
  /** After a refund, so the registrations above can unlock that removal. */
  onRefunded?: () => void;
}) {
  const { t } = useTranslation();
  const [confirmRefundAll, setConfirmRefundAll] = useState(false);
  const [search, setSearch] = useState("");
  const [day, setDay] = useState("");
  const [filterOpen, setFilterOpen] = useState(false);

  const {
    rows,
    people,
    feePercent,
    isLoading,
    isError,
    retry,
    peopleFailed,
    retryPeople,
    refundingIds,
    refundingAll,
  } = useParticipantsPayments(opportunityId);

  const visibleRows = useMemo(() => {
    const needle = search.trim().toLowerCase();
    return rows.filter((row) => {
      if (day && localDay(row.paid_at) !== day) return false;
      if (!needle) return true;
      const person = registrationPerson(people.get(String(row.registration_id)));
      return [row.user_name, row.user_email, person.phone, person.civilId]
        .filter(Boolean)
        .some((value) => String(value).toLowerCase().includes(needle));
    });
  }, [rows, people, search, day]);

  const clock = useClock(60_000);
  const refundAllAvailable = Boolean(clock) && canOpenRefundAll(rows, schedule, moment(clock));

  return (
    <section className="w-full pt-12" aria-labelledby="participants-payments-title">
      <div className="mb-6 flex flex-wrap items-start justify-between gap-4">
        <div className="hidden w-[180px] md:block" aria-hidden />
        <div className="flex-1 text-center">
          <h2
            id="participants-payments-title"
            className="text-2xl font-bold text-primary-5"
          >
            {t("COMMON.PARTICIPANTS_AND_PAYMENTS")}
          </h2>
          {feePercent !== null && <p className="mt-1 text-sm text-secondary-102">
            {t("COMMON.PAYMENTS_COMMISSION_NOTE", { percent: feePercent })}
          </p>}
        </div>
        <div className="flex w-[180px] flex-col items-center gap-1">
          <button
            type="button"
            onClick={() => setConfirmRefundAll(true)}
            disabled={!refundAllAvailable || refundingAll}
            aria-busy={refundingAll}
            className="inline-flex items-center gap-2 rounded-lg border border-[#E5484D] px-4 py-2 text-sm font-bold text-[#E5484D] hover:bg-[#E5484D0D]"
          >
            <FiRefreshCw className={refundingAll ? "animate-spin" : undefined} />
            {t("COMMON.REFUND_ALL_REQUEST")}
          </button>
          <span className="text-center text-[11px] text-secondary-102">
            {t("COMMON.REFUND_ALL_HINT")}
          </span>
        </div>
      </div>

      <div className="mb-6 flex flex-wrap items-center justify-center gap-3">
        <div className="w-full max-w-[420px] [&_.searchitms]:!w-full">
          <Searchbar
            value={search}
            onSearchChange={setSearch}
            placeholder={t("COMMON.SEARCH")}
            onFilterClick={() => setFilterOpen(true)}
            hasActiveFilters={Boolean(day)}
            onClearFilters={() => setDay("")}
          />
        </div>

      </div>

      {filterOpen && <PaymentsFilterModal
        day={day}
        onClose={() => setFilterOpen(false)}
        onApply={(nextDay) => { setDay(nextDay); setFilterOpen(false); }}
      />}

      {peopleFailed && rows.length > 0 && (
        <div role="alert" className="mb-4 flex flex-wrap items-center justify-center gap-3 rounded-xl bg-red-50 p-3 text-sm text-red-700">
          <span>{t("COMMON.PARTICIPANT_DETAILS_LOAD_FAILED")}</span>
          <Button size="small" onClick={retryPeople}>{t("COMMON.RETRY")}</Button>
        </div>
      )}
      {isLoading && rows.length === 0 ? (
        <div className="flex justify-center py-10">
          <Loader inline size="sm" />
        </div>
      ) : isError ? (
        <div role="alert" className="space-y-3 py-10 text-center">
          <p className="text-red-600">{t("COMMON.PAYMENTS_LOAD_FAILED")}</p>
          <Button size="small" onClick={retry}>{t("COMMON.RETRY")}</Button>
        </div>
      ) : rows.length === 0 ? (
        <p className="py-10 text-center text-secondary-102">
          {t("COMMON.NO_PARTICIPANTS_YET")}
        </p>
      ) : visibleRows.length === 0 ? (
        <p className="py-10 text-center text-secondary-102">
          {t("COMMON.NO_DATA")}
        </p>
      ) : (
        <div className="rounded-2xl bg-white p-2 shadow-[0_0_20px_#29246D0D]">
          <ParticipantsPaymentsTable
            rows={visibleRows}
            people={people}
            feePercent={feePercent}
            refundingIds={refundingIds}
            refundingAll={refundingAll}
          />
        </div>
      )}

      <PaidCancellationRequest opportunityId={opportunityId} mode="publisher"
        open={confirmRefundAll} onClose={() => setConfirmRefundAll(false)}
        onRequested={() => onRefunded?.()} />
    </section>
  );
}
