"use client";

import clsx from "clsx";
import { useState } from "react";
import { AlertTriangle, CheckCircle2 } from "lucide-react";
import { PageHeader, Panel, Select, Skeleton } from "@/components/ui/kit";
import { formatPaise } from "@/lib/format";
import { useApi } from "@/lib/use-api";

interface Rec {
  days: number;
  usage: { status: string; category: string; messages: number; estimated_paise: number; charged_paise: number; provider_cost_paise: number }[];
  wallet_mismatches: { organization_id: number; name: string; wallet_paise: number; ledger_paise: number }[];
  payments_stuck_created: number;
  payments_without_invoice: number;
  recharges_without_credit: number;
  refunds_pending: number;
}
const STATUS: Record<string, string> = { estimated: "Estimated, awaiting Meta", billable: "Confirmed, to be charged", charged: "Charged to wallet", free: "Free (confirmed by Meta)", void: "Not delivered, never charged" };

function Check({ ok, label, detail }: { ok: boolean; label: string; detail: string }) {
  return (
    <li className="flex items-start gap-3 py-3">
      {ok ? <CheckCircle2 className="mt-0.5 size-5 shrink-0 text-teal" /> : <AlertTriangle className="mt-0.5 size-5 shrink-0 text-amber" />}
      <div>
        <p className="font-medium">{label}</p>
        <p className="text-[13px] text-muted">{detail}</p>
      </div>
    </li>
  );
}

export default function ReconciliationPage() {
  const [days, setDays] = useState("30");
  const { data } = useApi<{ data: Rec }>(`/admin/reconciliation?days=${days}`);
  const r = data?.data;
  const charged = r?.usage.filter((u) => u.status === "charged" || u.status === "billable") ?? [];
  const totalCharged = charged.reduce((a, u) => a + u.charged_paise, 0);
  const totalCost = charged.reduce((a, u) => a + u.provider_cost_paise, 0);
  return (
    <>
      <PageHeader
        title="Reconciliation"
        description="Message estimates against what Meta confirmed, and integrity checks on wallets and payments."
        actions={
          <Select aria-label="Period" value={days} onChange={(e) => setDays(e.target.value)} className="w-40">
            <option value="7">Last 7 days</option>
            <option value="30">Last 30 days</option>
            <option value="90">Last 90 days</option>
          </Select>
        }
      />
      {!r ? (
        <Skeleton className="h-64" />
      ) : (
        <div className="grid grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_380px]">
          <Panel>
            <h2 className="border-b border-line px-5 py-3 font-semibold">Template message usage</h2>
            <div className="relative overflow-x-auto">
              <table className="w-full min-w-[640px] text-sm">
                <thead className="text-left text-[13px] text-muted">
                  <tr>
                    <th className="px-5 py-2.5 font-medium">State</th>
                    <th className="px-3 py-2.5 font-medium">Category</th>
                    <th className="px-3 py-2.5 text-right font-medium">Messages</th>
                    <th className="px-3 py-2.5 text-right font-medium">Estimated</th>
                    <th className="px-3 py-2.5 text-right font-medium">Charged</th>
                    <th className="px-5 py-2.5 text-right font-medium">Meta cost (est.)</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-line border-t border-line">
                  {r.usage.length === 0 && (
                    <tr>
                      <td colSpan={6} className="px-5 py-8 text-center text-muted">
                        No template messages in this period.
                      </td>
                    </tr>
                  )}
                  {r.usage.map((u) => (
                    <tr key={`${u.status}-${u.category}`}>
                      <td className="px-5 py-2.5">{STATUS[u.status] ?? u.status}</td>
                      <td className="px-3 py-2.5 capitalize">{u.category}</td>
                      <td className="tabular px-3 py-2.5 text-right">{u.messages.toLocaleString("en-IN")}</td>
                      <td className="tabular px-3 py-2.5 text-right text-muted">{formatPaise(u.estimated_paise)}</td>
                      <td className="tabular px-3 py-2.5 text-right">{formatPaise(u.charged_paise)}</td>
                      <td className="tabular px-5 py-2.5 text-right text-muted">{formatPaise(u.provider_cost_paise)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <dl className="grid grid-cols-3 gap-4 border-t border-line px-5 py-4 text-sm">
              <div>
                <dt className="text-[13px] text-muted">Charged to customers</dt>
                <dd className="tabular font-semibold">{formatPaise(totalCharged)}</dd>
              </div>
              <div>
                <dt className="text-[13px] text-muted">Meta cost (estimated)</dt>
                <dd className="tabular font-semibold">{formatPaise(totalCost)}</dd>
              </div>
              <div>
                <dt className="text-[13px] text-muted">Messaging margin</dt>
                <dd className={clsx("tabular font-semibold", totalCharged - totalCost < 0 && "text-brick")}>{formatPaise(totalCharged - totalCost)}</dd>
              </div>
            </dl>
            <p className="border-t border-line px-5 py-3 text-xs text-muted">Meta&apos;s cost uses the rates in Message pricing. Compare with your Meta invoice; the actual amount Meta bills is the source of truth.</p>
          </Panel>
          <Panel className="px-5 py-2">
            <h2 className="py-2 font-semibold">Integrity checks</h2>
            <ul className="divide-y divide-line text-sm">
              <Check ok={r.wallet_mismatches.length === 0} label="Wallets match their ledgers" detail={r.wallet_mismatches.length ? r.wallet_mismatches.map((m) => `${m.name}: wallet ${formatPaise(m.wallet_paise)}, ledger ${formatPaise(m.ledger_paise)}`).join("; ") : "Every balance equals the sum of its ledger entries."} />
              <Check ok={r.recharges_without_credit === 0} label="Every paid recharge was credited" detail={r.recharges_without_credit ? `${r.recharges_without_credit} paid recharge(s) have no wallet credit.` : "No paid recharge is missing its credit."} />
              <Check ok={r.payments_without_invoice === 0} label="Every payment has an invoice" detail={r.payments_without_invoice ? `${r.payments_without_invoice} paid payment(s) have no invoice.` : "All paid payments are invoiced."} />
              <Check ok={r.payments_stuck_created === 0} label="No checkouts left hanging" detail={r.payments_stuck_created ? `${r.payments_stuck_created} checkout(s) started over an hour ago without a result; Razorpay webhooks settle them if paid.` : "Every checkout older than an hour has a result."} />
              <Check ok={r.refunds_pending === 0} label="Refunds settled" detail={r.refunds_pending ? `${r.refunds_pending} refund(s) waiting for Razorpay to confirm.` : "No refunds are waiting."} />
            </ul>
          </Panel>
        </div>
      )}
    </>
  );
}
