"use client";

import Link from "next/link";
import { PageHeader, Skeleton } from "@/components/ui/kit";
import { bpToPct, StatTile } from "@/components/admin/common";
import { formatPaise } from "@/lib/format";
import { useApi } from "@/lib/use-api";
import type { Earnings } from "@/lib/types";

interface Overview {
  commission_rate_bp: number;
  max_markup_bp: number;
  customers: { total: number; active: number };
  subscriptions: Record<string, number>;
  this_month: { recharges_paise: number; subscriptions_paise: number; earnings_paise: number };
  earnings: Earnings;
}

export default function ResellerOverviewPage() {
  const { data } = useApi<{ data: Overview }>("/reseller/overview");
  const o = data?.data;
  return (
    <>
      <PageHeader title="Reseller overview" description="Your customers, what they paid this month, and what you've earned." />
      {!o ? (
        <Skeleton className="h-64" />
      ) : (
        <div className="space-y-6">
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <StatTile label="Customers" value={o.customers.total} sub={`${o.customers.active} active`} />
            <StatTile label="Paying plans" value={o.subscriptions.active ?? 0} sub={`${o.subscriptions.trialing ?? 0} on trial, ${(o.subscriptions.past_due ?? 0) + (o.subscriptions.suspended ?? 0)} need attention`} />
            <StatTile label="Recharges this month" value={formatPaise(o.this_month.recharges_paise, { compact: true })} sub="before GST" />
            <StatTile label="Plan payments this month" value={formatPaise(o.this_month.subscriptions_paise, { compact: true })} />
          </div>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <StatTile label="Earned this month" value={formatPaise(o.this_month.earnings_paise)} />
            <StatTile label="Earned in total" value={formatPaise(o.earnings.earned)} sub={`${formatPaise(o.earnings.commission)} commission, ${formatPaise(o.earnings.markup)} markup`} />
            <StatTile label="Paid out" value={formatPaise(o.earnings.paid_out)} />
            <StatTile label="Outstanding" value={formatPaise(o.earnings.outstanding)} />
          </div>
          <p className="text-sm text-muted">
            Your terms: {bpToPct(o.commission_rate_bp)} commission on what your customers pay (before GST), and you may price plans up to {bpToPct(o.max_markup_bp)} above list.{" "}
            <Link href="/reseller/plans" className="font-medium text-teal hover:underline">
              Set your prices
            </Link>
            .
          </p>
        </div>
      )}
    </>
  );
}
