"use client";

import Link from "next/link";
import { AlertTriangle } from "lucide-react";
import { PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { StatTile } from "@/components/admin/common";
import { formatPaise } from "@/lib/format";
import { useApi } from "@/lib/use-api";

interface Overview {
  customers: { total: number; active: number; suspended: number };
  resellers: number;
  subscriptions: Record<string, number>;
  whatsapp_numbers: number;
  messages_30d: { sent: number; delivered: number; read: number; failed: number; received: number };
  campaigns_30d: number;
  flow_runs_30d: number;
  bot_replies_sent_30d: number;
  money_30d: { recharges_paise: number; subscriptions_paise: number; tax_collected_paise: number; usage_charged_paise: number; refunds_paise: number };
  wallets_total_paise: number;
  months: { month: string; recharges_paise: number; subscriptions_paise: number; usage_paise: number }[];
  payments_configured: boolean;
  payments_mode: "razorpay" | "simulation";
  billing_configured: boolean;
}
const nf = new Intl.NumberFormat("en-IN");
const monthLabel = (m: string) => new Date(`${m}-01T00:00:00Z`).toLocaleDateString("en-IN", { month: "short", year: "numeric", timeZone: "UTC" });

export default function AdminOverviewPage() {
  const { data, error } = useApi<{ data: Overview }>("/admin/overview");
  const o = data?.data;
  return (
    <>
      <PageHeader title="Platform overview" description="Customers, messaging and money across Devwebs, last 30 days unless noted." />
      {error && <p className="rounded-md bg-brick-soft px-4 py-3 text-sm text-brick">{error}</p>}
      {!o ? (
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          {Array.from({ length: 8 }, (_, i) => (
            <Skeleton key={i} className="h-24" />
          ))}
        </div>
      ) : (
        <div className="space-y-6">
          {(!o.payments_configured || o.payments_mode === "simulation" || !o.billing_configured) && (
            <div className="flex items-start gap-3 rounded-lg bg-amber-soft px-4 py-3 text-sm text-amber" role="status">
              <AlertTriangle className="mt-0.5 size-4 shrink-0" />
              <div>
                {!o.billing_configured && <p>No plans exist yet, so subscriptions and limits aren&apos;t enforced. Create plans to start billing.</p>}
                {o.payments_mode === "simulation" ? (
                  <p>Payments run in test mode (PAYMENTS_PROVIDER=fake). No real money moves.</p>
                ) : (
                  !o.payments_configured && (
                    <p>
                      Razorpay keys are missing, so customers can&apos;t pay online.{" "}
                      <Link href="/admin/settings" className="font-medium underline">
                        Add them in billing settings
                      </Link>
                      .
                    </p>
                  )
                )}
              </div>
            </div>
          )}
          <section>
            <h2 className="mb-3 font-semibold">Customers and usage</h2>
            <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
              <StatTile label="Customers" value={nf.format(o.customers.total)} sub={`${nf.format(o.customers.active)} active, ${nf.format(o.customers.suspended)} suspended`} />
              <StatTile label="Resellers" value={nf.format(o.resellers)} />
              <StatTile label="Connected numbers" value={nf.format(o.whatsapp_numbers)} />
              <StatTile label="Subscriptions" value={nf.format(Object.values(o.subscriptions).reduce((a, b) => a + b, 0))} sub={`${o.subscriptions.active ?? 0} active, ${o.subscriptions.trialing ?? 0} trial, ${o.subscriptions.past_due ?? 0} due`} />
              <StatTile label="Messages sent" value={nf.format(o.messages_30d.sent)} sub={`${nf.format(o.messages_30d.delivered + o.messages_30d.read)} delivered, ${nf.format(o.messages_30d.read)} read`} />
              <StatTile label="Failed messages" value={nf.format(o.messages_30d.failed)} tone={o.messages_30d.failed ? "brick" : undefined} sub={`${nf.format(o.messages_30d.received)} received`} />
              <StatTile label="Campaigns launched" value={nf.format(o.campaigns_30d)} />
              <StatTile label="Automation" value={nf.format(o.flow_runs_30d + o.bot_replies_sent_30d)} sub={`${nf.format(o.flow_runs_30d)} flow runs, ${nf.format(o.bot_replies_sent_30d)} bot replies`} />
            </div>
          </section>
          <section>
            <h2 className="mb-3 font-semibold">Money</h2>
            <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
              <StatTile label="Wallet recharges" value={formatPaise(o.money_30d.recharges_paise, { compact: true })} sub="before GST" />
              <StatTile label="Subscriptions" value={formatPaise(o.money_30d.subscriptions_paise, { compact: true })} sub="online and wallet" />
              <StatTile label="Usage charged" value={formatPaise(o.money_30d.usage_charged_paise, { compact: true })} sub="confirmed by Meta" />
              <StatTile label="GST collected" value={formatPaise(o.money_30d.tax_collected_paise, { compact: true })} />
              <StatTile label="Refunds" value={formatPaise(o.money_30d.refunds_paise, { compact: true })} />
              <StatTile label="Customer wallets" value={formatPaise(o.wallets_total_paise, { compact: true })} sub="total balance now" />
            </div>
          </section>
          <Panel>
            <h2 className="border-b border-line px-5 py-3 font-semibold">Revenue by month</h2>
            <div className="relative overflow-x-auto">
              <table className="w-full min-w-[560px] text-sm">
                <thead className="text-left text-[13px] text-muted">
                  <tr>
                    <th className="px-5 py-2.5 font-medium">Month</th>
                    <th className="px-3 py-2.5 text-right font-medium">Recharges</th>
                    <th className="px-3 py-2.5 text-right font-medium">Subscriptions</th>
                    <th className="px-5 py-2.5 text-right font-medium">Usage charged</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-line border-t border-line">
                  {o.months.map((m) => (
                    <tr key={m.month}>
                      <td className="px-5 py-2.5">{monthLabel(m.month)}</td>
                      <td className="tabular px-3 py-2.5 text-right">{formatPaise(m.recharges_paise)}</td>
                      <td className="tabular px-3 py-2.5 text-right">{formatPaise(m.subscriptions_paise)}</td>
                      <td className="tabular px-5 py-2.5 text-right">{formatPaise(m.usage_paise)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <p className="border-t border-line px-5 py-3 text-xs text-muted">Recharges become platform revenue as messages are used; subscriptions are recognised when paid. Amounts are before GST.</p>
          </Panel>
        </div>
      )}
    </>
  );
}
