"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import { Alert, Button, Card, EmptyState, Input, Modal, PageHeader, LoadingArea, Select, StatCard } from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatBDT, formatDate } from "@/lib/utils";
import { IconDollar, IconFile, IconWallet, IconBuilding, IconMessageCircle } from "@/components/icons";
import { esc, instLogoChip, openPrintWindow } from "@/lib/print";

interface FeesData {
  statement: {
    id: number;
    title: string;
    headName: string | null;
    headNameBn: string | null;
    amount: number;
    paid: number;
    due: number;
    status: "PAID" | "PARTIAL" | "DUE";
    dueDate: string | null;
    month: string | null;
  }[];
  payments: {
    id: number;
    invoiceNo: string;
    amount: number;
    method: string;
    paidAt: string;
    title: string | null;
  }[];
  totals: { assigned: number; paid: number; due: number };
}

interface MeStudentInfo {
  student: { id: number; roll: string; name: string; nameBn: string | null; className: string | null; classNameBn: string | null; sectionName: string | null } | null;
  institution: { name: string; address: string; phone: string; logo: string | null } | null;
}

interface FeeClaim {
  id: number;
  amount: number;
  method: string;
  accountLabel: string | null;
  details: Record<string, string> | null;
  note: string | null;
  status: "PENDING" | "APPROVED" | "REJECTED";
  decisionNote: string | null;
  decidedAt: string | null;
  createdAt: string;
  feeTitle: string | null;
  month: string | null;
  invoiceNo: string | null;
}

type StatusFilter = "ALL" | "DUE" | "PARTIAL" | "PAID";

const ONLINE_METHODS = ["BKASH", "NAGAD", "ROCKET", "BANK_TRANSFER", "CARD"];
const MOBILE_PROVIDERS = ["BKASH", "NAGAD", "ROCKET"];

/** Student/parent: itemized fee statement (filterable, overdue-flagged,
    printable) and payment history with per-payment receipts. */
export default function MeFeesPage() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<FeesData>("/api/me/fees");
  const accounts = useApi<{ accounts: MeAccount[] }>("/api/me/collection-accounts");
  const me = useApi<MeStudentInfo>("/api/me/student");
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("ALL");
  const [receiptId, setReceiptId] = useState<number | null>(null);

  // online payment claim — submit the transaction reference of a payment
  // made through one of the institution's collection accounts
  const claims = useApi<{ claims: FeeClaim[] }>("/api/me/fees/claims");
  const [payOpen, setPayOpen] = useState(false);
  const [payForm, setPayForm] = useState<{
    feeScheduleId: string;
    amount: string;
    method: string;
    accountLabel: string;
    details: Record<string, string>;
    note: string;
  }>({ feeScheduleId: "", amount: "", method: "BKASH", accountLabel: "", details: {}, note: "" });
  const [paySaving, setPaySaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const d = data;
  const today = new Date().toISOString().slice(0, 10);

  /** overdue = unpaid (fully or partly) with a due date in the past */
  const isOverdue = (s: NonNullable<FeesData["statement"][number]>) =>
    s.due > 0 && s.dueDate != null && s.dueDate.slice(0, 10) < today;

  /** unpaid items first (most urgent due date on top), then cleared ones */
  const statement = useMemo(() => {
    const items = [...(d?.statement ?? [])];
    items.sort((a, b) => {
      const ua = a.due > 0 ? 0 : 1;
      const ub = b.due > 0 ? 0 : 1;
      if (ua !== ub) return ua - ub;
      if (ua === 0) {
        const da = a.dueDate ?? "9999-12-31";
        const db = b.dueDate ?? "9999-12-31";
        if (da !== db) return da < db ? -1 : 1;
      }
      return b.id - a.id;
    });
    return statusFilter === "ALL" ? items : items.filter((s) => s.status === statusFilter);
  }, [d, statusFilter]);

  const counts = useMemo(() => {
    const items = d?.statement ?? [];
    return {
      ALL: items.length,
      DUE: items.filter((s) => s.status === "DUE").length,
      PARTIAL: items.filter((s) => s.status === "PARTIAL").length,
      PAID: items.filter((s) => s.status === "PAID").length,
    };
  }, [d]);

  const overdueCount = (d?.statement ?? []).filter(isOverdue).length;

  // ----- online payment claim -----
  function payRequiredFields(): string[] {
    if (MOBILE_PROVIDERS.includes(payForm.method)) return ["txnId"];
    if (payForm.method === "BANK_TRANSFER") return ["bankName", "refNo"];
    if (payForm.method === "CARD") return ["refNo"];
    return [];
  }
  const payMissing = payRequiredFields().filter((k) => !(payForm.details[k] ?? "").trim());
  const setPayDetail = (key: string, value: string) =>
    setPayForm((f) => ({ ...f, details: { ...f.details, [key]: value } }));

  /** collection accounts that can receive the chosen method */
  const payAccounts = (accounts.data?.accounts ?? []).filter((a) =>
    MOBILE_PROVIDERS.includes(payForm.method)
      ? a.type === "MOBILE"
      : payForm.method === "BANK_TRANSFER"
        ? a.type === "BANK"
        : a.type !== "MOBILE"
  );

  function openPay(feeScheduleId?: number, dueAmount?: number) {
    setMessage(null);
    setPayForm({
      feeScheduleId: feeScheduleId ? String(feeScheduleId) : "",
      amount: dueAmount && dueAmount > 0 ? String(dueAmount) : "",
      method: "BKASH",
      accountLabel: "",
      details: {},
      note: "",
    });
    setPayOpen(true);
  }

  async function submitClaim() {
    if (paySaving) return;
    setPaySaving(true);
    try {
      await api("/api/me/fees/claims", {
        method: "POST",
        body: JSON.stringify({
          feeScheduleId: payForm.feeScheduleId ? Number(payForm.feeScheduleId) : null,
          amount: Number(payForm.amount),
          method: payForm.method,
          accountLabel: payForm.accountLabel || null,
          details: payForm.details,
          note: payForm.note || null,
        }),
      });
      setPayOpen(false);
      setMessage({ type: "success", text: t.me.claimSubmitted });
      claims.reload();
    } catch (e) {
      const msg = e instanceof Error ? e.message : "";
      setMessage({
        type: "error",
        text:
          msg === "CLAIM_EXISTS"
            ? t.me.claimExists
            : msg === "AMOUNT_EXCEEDS"
              ? t.me.claimAmountExceeds
              : t.common.tryAgain,
      });
    } finally {
      setPaySaving(false);
    }
  }

  function printStatement() {
    if (!d) return;
    const m = me.data;
    const cls = m?.student ? (locale === "bn" && m.student.classNameBn ? m.student.classNameBn : m.student.className) : null;
    const rows = (d.statement ?? [])
      .map(
        (s) => `<tr>
        <td style="border:1px solid #d9e1ec;padding:5px 9px">${esc(s.title)}${(locale === "bn" && s.headNameBn ? s.headNameBn : s.headName) ? `<div style="font-size:10px;color:#718096">${esc(locale === "bn" && s.headNameBn ? s.headNameBn : s.headName ?? "")}</div>` : ""}</td>
        <td style="border:1px solid #d9e1ec;padding:5px 9px">${esc(s.month ?? "—")}</td>
        <td style="border:1px solid #d9e1ec;padding:5px 9px">${s.dueDate ? formatDate(s.dueDate, locale) : "—"}</td>
        <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${formatBDT(s.amount, locale)}</td>
        <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${formatBDT(s.paid, locale)}</td>
        <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${formatBDT(s.due, locale)}</td>
        <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:center">${esc(t.me[s.status.toLowerCase() as keyof typeof t.me] ?? s.status)}</td>
      </tr>`,
      )
      .join("");
    const body = `
<div class="doc">
  <div style="display:flex;align-items:center;gap:12px;border-bottom:2px solid #24695c;padding-bottom:10px;margin-bottom:12px">
    ${instLogoChip(m?.institution?.logo ?? null, 44)}
    <div>
      <p style="margin:0;font-size:17px;font-weight:700;color:#1d4f45">${esc(m?.institution?.name ?? "")}</p>
      <p style="margin:0;font-size:11px;color:#5b6b79">${esc(m?.institution?.address ?? "")}${m?.institution?.phone ? " · " + esc(m.institution.phone) : ""}</p>
    </div>
    <span style="margin-left:auto;font-size:11px;font-weight:700;color:#24695c;border:1px solid #24695c66;border-radius:8px;padding:4px 10px;background:#fff">${esc(t.me.feeStatement)}</span>
  </div>
  <p style="margin:0 0 10px;font-size:12px;color:#5b6b79">
    ${esc(m?.student?.name ?? "")}${m?.student?.roll ? ` · ${esc(t.portal.identityPage.roll)} ${esc(m.student.roll)}` : ""}${cls ? ` · ${esc(cls)}` : ""}
  </p>
  <table style="width:100%;font-size:11.5px">
    <thead><tr style="background:#f4f7fa">
      <th style="border:1px solid #d9e1ec;padding:5px 9px;text-align:left">${esc(t.me.feeItem)}</th>
      <th style="border:1px solid #d9e1ec;padding:5px 9px;text-align:left">${esc(t.common.month)}</th>
      <th style="border:1px solid #d9e1ec;padding:5px 9px;text-align:left">${esc(t.me.dueDateCol)}</th>
      <th style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${esc(t.common.amount)}</th>
      <th style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${esc(t.common.paid)}</th>
      <th style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${esc(t.common.due)}</th>
      <th style="border:1px solid #d9e1ec;padding:5px 9px">${esc(t.common.status)}</th>
    </tr></thead>
    <tbody>${rows}</tbody>
    <tfoot><tr style="background:#f4f7fa;font-weight:700">
      <td style="border:1px solid #d9e1ec;padding:5px 9px" colspan="3">${esc(t.me.grandTotal)}</td>
      <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${formatBDT(d.totals.assigned, locale)}</td>
      <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${formatBDT(d.totals.paid, locale)}</td>
      <td style="border:1px solid #d9e1ec;padding:5px 9px;text-align:right">${formatBDT(d.totals.due, locale)}</td>
      <td style="border:1px solid #d9e1ec;padding:5px 9px"></td>
    </tr></tfoot>
  </table>
</div>`;
    openPrintWindow(t.me.feeStatement, locale, body);
  }

  async function printReceipt(p: FeesData["payments"][number]) {
    setReceiptId(p.id);
    try {
      const m = me.data;
      const inst = m?.institution;
      const cls = m?.student ? (locale === "bn" && m.student.classNameBn ? m.student.classNameBn : m.student.className) : null;
      const body = `
<div class="doc" style="max-width:560px;border:2px solid #24695c;border-radius:10px;overflow:hidden">
  <div style="background:#f4f7fa;border-bottom:2px solid #24695c;padding:12px 20px;display:flex;align-items:center;gap:12px">
    ${instLogoChip(inst?.logo ?? null, 40)}
    <div>
      <p style="margin:0;font-size:16px;font-weight:700;color:#1d4f45">${esc(inst?.name ?? "")}</p>
      <p style="margin:0;font-size:10.5px;color:#5b6b79">${esc(inst?.address ?? "")}${inst?.phone ? " · " + esc(inst.phone) : ""}</p>
    </div>
    <span style="margin-left:auto;font-size:11px;font-weight:700;color:#24695c;border:1px solid #24695c66;border-radius:8px;padding:4px 10px;background:#fff">${esc(t.me.receiptTitle)}</span>
  </div>
  <div style="padding:16px 20px">
    <div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:10px">
      <span>${esc(t.common.invoice)}: <b>${esc(p.invoiceNo)}</b></span>
      <span>${esc(t.common.date)}: <b>${formatDate(p.paidAt, locale)}</b></span>
    </div>
    <table style="width:100%;font-size:12px">
      <tr>
        <td style="padding:4px 0;color:#718096;width:40%">${esc(t.me.studentName)}</td>
        <td style="padding:4px 0;font-weight:700">${esc(m?.student?.name ?? "—")}${m?.student?.roll ? ` (${esc(m.student.roll)})` : ""}</td>
      </tr>
      ${cls ? `<tr>
        <td style="padding:4px 0;color:#718096">${esc(t.portal.studentsPage.classLabel)}</td>
        <td style="padding:4px 0;font-weight:700">${esc(cls)}</td>
      </tr>` : ""}
      <tr>
        <td style="padding:4px 0;color:#718096">${esc(t.me.feeItem)}</td>
        <td style="padding:4px 0;font-weight:700">${esc(p.title ?? "—")}</td>
      </tr>
      <tr>
        <td style="padding:4px 0;color:#718096">${esc(t.common.method)}</td>
        <td style="padding:4px 0;font-weight:700">${esc(t.methods[p.method as keyof typeof t.methods] ?? p.method)}</td>
      </tr>
      <tr>
        <td style="padding:8px 0;color:#718096;border-top:1px dashed #c3d4cf">${esc(t.common.amount)}</td>
        <td style="padding:8px 0;font-size:16px;font-weight:800;color:#2e8b57;border-top:1px dashed #c3d4cf">${formatBDT(p.amount, locale)}</td>
      </tr>
    </table>
    <div style="display:flex;justify-content:space-between;margin-top:26px;font-size:11px;color:#718096">
      <span>${esc(t.me.receiptReceivedBy)}: ____________________</span>
      <span>${esc(inst?.name ?? "")}: ____________________</span>
    </div>
  </div>
</div>`;
      openPrintWindow(t.me.receiptTitle, locale, body);
    } finally {
      setReceiptId(null);
    }
  }

  if (loading) {
    return (
      <div>
        <PageHeader title={t.me.feesTitle} subtitle={t.me.feesSubtitle} />
        <LoadingArea label={t.common.loading} />
      </div>
    );
  }

  const filters: StatusFilter[] = ["ALL", "DUE", "PARTIAL", "PAID"];
  const filterLabel = (f: StatusFilter) =>
    f === "ALL" ? t.me.filterAll : t.me[f.toLowerCase() as keyof typeof t.me] ?? f;

  return (
    <div>
      <PageHeader
        title={t.me.feesTitle}
        subtitle={t.me.feesSubtitle}
        action={
          <div className="d-flex gap-2">
            {(d?.statement ?? []).some((s) => s.due > 0) && (
              <Button size="sm" onClick={() => openPay()}>
                <IconWallet className="svg-14" />
                <span className="ms-1">{t.me.payOnline}</span>
              </Button>
            )}
            {(d?.statement ?? []).length > 0 && (
              <Button size="sm" variant="secondary" onClick={printStatement}>
                <IconFile className="svg-14" />
                <span className="ms-1">{t.me.printStatement}</span>
              </Button>
            )}
          </div>
        }
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      {(accounts.data?.accounts ?? []).length > 0 && (
        <div className="card mb-4">
          <div className="card-header">
            <h5 className="mb-0 f-w-700">{t.me.payWhereTitle}</h5>
            <p className="mb-0 ems-fs-12 text-muted">{t.me.payWhereSubtitle}</p>
          </div>
          <div className="card-body">
            <div className="row g-3">
              {accounts.data!.accounts.map((acc, i) => (
                <MeAccountCard key={i} acc={acc} />
              ))}
            </div>
          </div>
        </div>
      )}

      <div className="row g-4 mb-4">
        <div className="col-xl-4 col-md-4">
          <StatCard label={t.portal.studentsPage.totalAssigned} value={formatBDT(d?.totals.assigned ?? 0, locale)} icon={<IconWallet />} accent="blue" />
        </div>
        <div className="col-xl-4 col-md-4">
          <StatCard label={t.portal.dashboard.totalPaid} value={formatBDT(d?.totals.paid ?? 0, locale)} icon={<IconDollar />} accent="teal" />
        </div>
        <div className="col-xl-4 col-md-4">
          <StatCard
            label={t.portal.dashboard.outstandingDue}
            value={formatBDT(d?.totals.due ?? 0, locale)}
            icon={<IconWallet />}
            accent={(d?.totals.due ?? 0) > 0 ? "red" : "sky"}
            hint={overdueCount > 0 ? `${overdueCount} ${t.me.overdueItems}` : undefined}
          />
        </div>
      </div>

      <Card
        title={t.me.feeStatement}
        icon={<IconWallet className="svg-20" />}
        className="mb-4"
        action={
          (d?.statement ?? []).length > 0 ? (
            <div className="btn-group btn-group-sm">
              {filters.map((f) => (
                <button
                  key={f}
                  type="button"
                  className={`btn f-w-700 ${statusFilter === f ? "btn-primary" : "btn-outline-secondary"}`}
                  onClick={() => setStatusFilter(f)}
                >
                  {filterLabel(f)}{f !== "ALL" ? ` (${counts[f]})` : ` (${counts.ALL})`}
                </button>
              ))}
            </div>
          ) : undefined
        }
      >
        {(d?.statement ?? []).length === 0 ? (
          <EmptyState icon={<IconWallet />} title={t.me.noFees} />
        ) : statement.length === 0 ? (
          <EmptyState icon={<IconWallet />} title={t.me.noFeesInFilter} />
        ) : (
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.me.feeItem}</th>
                  <th>{t.common.month}</th>
                  <th>{t.me.dueDateCol}</th>
                  <th className="text-end">{t.common.amount}</th>
                  <th className="text-end">{t.common.paid}</th>
                  <th className="text-end">{t.common.due}</th>
                  <th className="text-center">{t.common.status}</th>
                </tr>
              </thead>
              <tbody>
                {statement.map((s) => (
                  <tr key={s.id}>
                    <td className="f-w-600 ems-fs-13">
                      {s.title}
                      {(locale === "bn" && s.headNameBn ? s.headNameBn : s.headName) && (
                        <span className="d-block ems-fs-11 text-muted">
                          {locale === "bn" && s.headNameBn ? s.headNameBn : s.headName}
                        </span>
                      )}
                    </td>
                    <td className="ems-fs-12 text-muted">{s.month ?? "—"}</td>
                    <td className="ems-fs-12 text-muted">
                      {s.dueDate ? formatDate(s.dueDate, locale) : "—"}
                      {isOverdue(s) && <span className="badge badge-danger ms-1">{t.me.overdueBadge}</span>}
                    </td>
                    <td className="text-end f-w-700">{formatBDT(s.amount, locale)}</td>
                    <td className="text-end text-success f-w-600">{formatBDT(s.paid, locale)}</td>
                    <td className={`text-end f-w-600 ${s.due > 0 ? "text-danger" : "text-muted"}`}>
                      {formatBDT(s.due, locale)}
                    </td>
                    <td className="text-center">
                      <span
                        className={`badge ${
                          s.status === "PAID" ? "badge-success" : s.status === "PARTIAL" ? "badge-warning" : "badge-danger"
                        }`}
                      >
                        {t.me[s.status.toLowerCase() as keyof typeof t.me] ?? s.status}
                      </span>
                      {s.due > 0 && (
                        <button
                          type="button"
                          className="btn btn-sm btn-soft-primary d-block mt-1 mx-auto ems-fs-11 f-w-700"
                          onClick={() => openPay(s.id, s.due)}
                        >
                          {t.me.payOnline}
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="ems-table-head">
                  <td className="f-w-700" colSpan={3}>{t.me.grandTotal}</td>
                  <td className="text-end f-w-700">{formatBDT(d?.totals.assigned ?? 0, locale)}</td>
                  <td className="text-end f-w-700">{formatBDT(d?.totals.paid ?? 0, locale)}</td>
                  <td className="text-end f-w-700">{formatBDT(d?.totals.due ?? 0, locale)}</td>
                  <td />
                </tr>
              </tfoot>
            </table>
          </div>
        )}
      </Card>

      {(claims.data?.claims ?? []).length > 0 && (
        <Card title={t.me.claimsTitle} icon={<IconWallet className="svg-20" />} className="mb-4">
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.common.date}</th>
                  <th>{t.me.feeItem}</th>
                  <th className="text-center">{t.common.method}</th>
                  <th>{t.me.claimRefCol}</th>
                  <th className="text-end">{t.common.amount}</th>
                  <th className="text-center">{t.common.status}</th>
                </tr>
              </thead>
              <tbody>
                {(claims.data?.claims ?? []).map((c) => {
                  const ref = c.details?.txnId ?? c.details?.refNo ?? "—";
                  return (
                    <tr key={c.id}>
                      <td className="ems-fs-12 text-muted">{formatDate(c.createdAt, locale)}</td>
                      <td className="f-w-600 ems-fs-13">
                        {c.feeTitle ?? t.me.claimGeneralItem}
                        {c.invoiceNo && (
                          <span className="d-block ems-fs-11 text-muted">
                            {t.common.invoice}: <code className="ems-invoice-badge">{c.invoiceNo}</code>
                          </span>
                        )}
                        {c.decisionNote && c.status === "REJECTED" && (
                          <span className="d-block ems-fs-11 text-danger">{c.decisionNote}</span>
                        )}
                      </td>
                      <td className="text-center ems-fs-13">
                        {t.methods[c.method as keyof typeof t.methods] ?? c.method}
                        {c.accountLabel && <span className="d-block ems-fs-11 text-muted">{c.accountLabel}</span>}
                      </td>
                      <td>
                        <code className="ems-invoice-badge">{ref}</code>
                      </td>
                      <td className="text-end f-w-700">{formatBDT(c.amount, locale)}</td>
                      <td className="text-center">
                        <span
                          className={`badge ${
                            c.status === "APPROVED" ? "badge-success" : c.status === "REJECTED" ? "badge-danger" : "badge-warning"
                          }`}
                        >
                          {c.status === "APPROVED" ? t.me.claimApproved : c.status === "REJECTED" ? t.me.claimRejected : t.me.claimPending}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <p className="ems-fs-11 text-muted mt-2 mb-0">{t.me.claimsHint}</p>
        </Card>
      )}

      <Card title={t.me.paymentHistory} icon={<IconDollar className="svg-20" />}>
        {(d?.payments ?? []).length === 0 ? (
          <EmptyState icon={<IconDollar />} title={t.me.noPayments} />
        ) : (
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.common.invoice}</th>
                  <th>{t.me.feeItem}</th>
                  <th>{t.common.date}</th>
                  <th className="text-center">{t.common.method}</th>
                  <th className="text-end">{t.common.amount}</th>
                  <th className="text-end">{t.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {(d?.payments ?? []).map((p) => (
                  <tr key={p.id}>
                    <td>
                      <code className="ems-invoice-badge">{p.invoiceNo}</code>
                    </td>
                    <td className="ems-fs-13">{p.title ?? "—"}</td>
                    <td className="ems-fs-12 text-muted">{formatDate(p.paidAt, locale)}</td>
                    <td className="text-center ems-fs-13">
                      {t.methods[p.method as keyof typeof t.methods] ?? p.method}
                    </td>
                    <td className="text-end f-w-700 text-success">{formatBDT(p.amount, locale)}</td>
                    <td className="text-end">
                      <button
                        type="button"
                        className="btn btn-sm btn-soft-secondary ems-fs-12 f-w-600"
                        disabled={receiptId === p.id}
                        onClick={() => printReceipt(p)}
                      >
                        <IconFile className="svg-14" />
                        <span className="ms-1">{t.me.receiptBtn}</span>
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {/* Pay Online modal — submit the transaction reference for verification */}
      <Modal open={payOpen} onClose={() => setPayOpen(false)} title={t.me.payOnlineTitle} wide>
        <p className="ems-fs-12 text-muted mb-3">{t.me.payOnlineHint}</p>
        <div className="row g-3">
          <div className="col-md-7">
            <Select
              label={t.me.feeItem}
              value={payForm.feeScheduleId}
              onChange={(e) => {
                const id = e.target.value;
                const item = (d?.statement ?? []).find((s) => String(s.id) === id);
                setPayForm((f) => ({ ...f, feeScheduleId: id, amount: item && item.due > 0 ? String(item.due) : f.amount }));
              }}
            >
              <option value="">{t.me.claimGeneralItem}</option>
              {(d?.statement ?? []).filter((s) => s.due > 0).map((s) => (
                <option key={s.id} value={s.id}>
                  {s.title}{s.month ? ` (${s.month})` : ""} — {t.common.due}: {formatBDT(s.due, locale)}
                </option>
              ))}
            </Select>
          </div>
          <div className="col-md-5">
            <Input
              label={`${t.common.amount} *`}
              type="number"
              min="1"
              required
              value={payForm.amount}
              onChange={(e) => setPayForm((f) => ({ ...f, amount: e.target.value }))}
            />
          </div>
          <div className="col-md-6">
            <Select
              label={`${t.common.method} *`}
              value={payForm.method}
              onChange={(e) => setPayForm((f) => ({ ...f, method: e.target.value, accountLabel: "", details: {} }))}
            >
              {ONLINE_METHODS.map((m) => (
                <option key={m} value={m}>
                  {t.methods[m as keyof typeof t.methods] ?? m}
                </option>
              ))}
            </Select>
          </div>
          <div className="col-md-6">
            <Select
              label={t.me.payAccount}
              value={payForm.accountLabel}
              onChange={(e) => setPayForm((f) => ({ ...f, accountLabel: e.target.value }))}
            >
              <option value="">—</option>
              {payAccounts.map((a, i) => (
                <option key={i} value={a.label}>
                  {a.label} — {a.accountNumber}
                </option>
              ))}
            </Select>
          </div>
        </div>

        <div className="p-3 mt-1 mb-3 rounded" style={{ background: "rgba(36,105,92,0.05)" }}>
          <p className="ems-fs-11 f-w-700 text-uppercase text-muted mb-2">{t.me.claimRefCol}</p>
          {MOBILE_PROVIDERS.includes(payForm.method) && (
            <div className="row g-2">
              <div className="col-sm-6">
                <Input
                  label={`${t.me.claimTxnId} *`}
                  value={payForm.details.txnId ?? ""}
                  placeholder="8N7A1B2C"
                  onChange={(e) => setPayDetail("txnId", e.target.value)}
                />
              </div>
              <div className="col-sm-6">
                <Input
                  label={t.portal.feesPage.cfAccount}
                  value={payForm.details.account ?? ""}
                  placeholder="01XXXXXXXXX"
                  onChange={(e) => setPayDetail("account", e.target.value)}
                />
              </div>
            </div>
          )}
          {payForm.method === "BANK_TRANSFER" && (
            <div className="row g-2">
              <div className="col-sm-6">
                <Input
                  label={`${t.portal.feesPage.cfBank} *`}
                  value={payForm.details.bankName ?? ""}
                  onChange={(e) => setPayDetail("bankName", e.target.value)}
                />
              </div>
              <div className="col-sm-6">
                <Input
                  label={t.portal.feesPage.cfBranch}
                  value={payForm.details.branch ?? ""}
                  onChange={(e) => setPayDetail("branch", e.target.value)}
                />
              </div>
              <div className="col-sm-6">
                <Input
                  label={`${t.portal.feesPage.cfRef} *`}
                  value={payForm.details.refNo ?? ""}
                  onChange={(e) => setPayDetail("refNo", e.target.value)}
                />
              </div>
              <div className="col-sm-6">
                <Input
                  label={t.portal.feesPage.cfAcNo}
                  value={payForm.details.account ?? ""}
                  onChange={(e) => setPayDetail("account", e.target.value)}
                />
              </div>
            </div>
          )}
          {payForm.method === "CARD" && (
            <div className="row g-2">
              <div className="col-sm-4">
                <Select
                  label={t.portal.feesPage.cfCardType}
                  value={payForm.details.cardType ?? ""}
                  onChange={(e) => setPayDetail("cardType", e.target.value)}
                >
                  <option value="">—</option>
                  <option value="credit">{t.portal.feesPage.cfCredit}</option>
                  <option value="debit">{t.portal.feesPage.cfDebit}</option>
                  <option value="prepaid">{t.portal.feesPage.cfPrepaid}</option>
                </Select>
              </div>
              <div className="col-sm-4">
                <Input
                  label={t.portal.feesPage.cfLast4}
                  value={payForm.details.last4 ?? ""}
                  placeholder="1234"
                  maxLength={4}
                  onChange={(e) => setPayDetail("last4", e.target.value.replace(/\D/g, ""))}
                />
              </div>
              <div className="col-sm-4">
                <Input
                  label={`${t.portal.feesPage.cfApproval} *`}
                  value={payForm.details.refNo ?? ""}
                  onChange={(e) => setPayDetail("refNo", e.target.value)}
                />
              </div>
            </div>
          )}
        </div>

        <Input
          label={t.common.note}
          value={payForm.note}
          onChange={(e) => setPayForm((f) => ({ ...f, note: e.target.value }))}
        />

        <div className="d-flex justify-content-end gap-2 pt-3">
          <Button variant="secondary" onClick={() => setPayOpen(false)}>
            {t.common.cancel}
          </Button>
          <Button onClick={submitClaim} loading={paySaving} disabled={!payForm.amount || Number(payForm.amount) <= 0 || payMissing.length > 0}>
            <IconWallet className="svg-16" />
            <span className="ms-1">{t.me.payOnlineSubmit}</span>
          </Button>
        </div>
      </Modal>
    </div>
  );
}


interface MeAccount {
  type: "MOBILE" | "BANK" | "OTHER";
  provider: string | null;
  accountType: string | null;
  label: string;
  accountName: string | null;
  accountNumber: string;
  branch: string | null;
  routingNo: string | null;
  note: string | null;
}

/** One receiving account with a copy button for the number. */
function MeAccountCard({ acc }: { acc: MeAccount }) {
  const { t, locale } = useLang();
  const [copied, setCopied] = useState(false);

  async function copy() {
    try {
      await navigator.clipboard.writeText(acc.accountNumber);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {
      /* clipboard unavailable */
    }
  }

  const title =
    acc.type === "MOBILE" && acc.provider
      ? t.methods[acc.provider as keyof typeof t.methods] ?? acc.label
      : acc.label;

  return (
    <div className="col-lg-4 col-md-6">
      <div className="p-3 h-100 rounded" style={{ background: "rgba(36,105,92,0.05)", border: "1px solid rgba(36,105,92,0.12)" }}>
        <div className="d-flex align-items-center gap-2 mb-2">
          <span
            className="rounded-circle d-inline-flex align-items-center justify-content-center"
            style={{ width: 34, height: 34, background: "#24695c", color: "#fff" }}
          >
            {acc.type === "MOBILE" ? <IconMessageCircle className="svg-16" /> : acc.type === "BANK" ? <IconBuilding className="svg-16" /> : <IconWallet className="svg-16" />}
          </span>
          <div className="min-w-0">
            <div className="f-w-700 ems-fs-13 text-truncate">{title}</div>
            {acc.type === "MOBILE" && acc.accountType && (
              <span className="badge badge-secondary">{acc.accountType === "MERCHANT" ? t.me.payMerchant : t.me.payPersonal}</span>
            )}
          </div>
        </div>
        <div className="d-flex align-items-center justify-content-between gap-2 mb-1">
          <code className="ems-invoice-badge" style={{ fontSize: 13 }}>{acc.accountNumber}</code>
          {acc.accountNumber !== "—" && (
            <button type="button" className="btn btn-sm btn-outline-secondary ems-fs-11 f-w-600" onClick={copy}>
              {copied ? t.me.payCopied : t.me.payCopy}
            </button>
          )}
        </div>
        {acc.accountName && <div className="ems-fs-12 text-muted">{acc.accountName}</div>}
        {acc.branch && <div className="ems-fs-12 text-muted">{acc.branch}</div>}
        {acc.routingNo && (
          <div className="ems-fs-11 text-muted">{t.me.payRouting}: {acc.routingNo}</div>
        )}
        {acc.note && <div className="ems-fs-11 text-muted mt-1">{acc.note}</div>}
      </div>
    </div>
  );
}
