import { notFound } from "next/navigation";
import Shell from "@/components/Shell";
import { requireSession, asMembershipRow } from "@/lib/session";
import { can } from "@/lib/rbac";
import { getOrgUsage } from "@/lib/data/org";
import { listInvoices } from "@/lib/data/billing";
import { PageHeader, Card, ListRow, Badge } from "@/components/ui";

function UsageBar({ label, used, limit, unit = "" }: { label: string; used: number; limit: number; unit?: string }) {
  const pct = Math.min(100, Math.round((used / Math.max(limit, 1)) * 100));
  return (
    <Card>
      <div className="flex justify-between text-xs text-text-secondary mb-2">
        <span>{label}</span>
        <span>
          {used}
          {unit} / {limit}
          {unit}
        </span>
      </div>
      <div className="h-1.5 bg-border-input rounded-full overflow-hidden">
        <div className="h-full bg-accent" style={{ width: `${pct}%` }} />
      </div>
    </Card>
  );
}

export default async function BillingPage() {
  const session = await requireSession();
  const m = asMembershipRow(session);
  if (!can.manageBilling(m)) notFound();

  const { org, sitesUsed, seatsUsed } = getOrgUsage(session.orgId);
  const invoices = listInvoices(session.orgId) as any[];

  return (
    <Shell session={session} active="/billing">
      <PageHeader title="Billing" description="Plan usage and invoice history" />

      <Card className="flex items-center justify-between flex-wrap gap-3.5 mb-5 rounded-2xl">
        <div>
          <div className="font-heading text-[19px] font-bold">{org.plan_name} plan</div>
          <div className="text-[12.5px] text-text-secondary mt-1">
            Renews {new Date(org.renews_at).toLocaleDateString()}
          </div>
        </div>
        <div className="font-heading text-[22px] font-bold">
          ${(org.price_cents / 100).toFixed(0)}/mo
        </div>
      </Card>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5 mb-6">
        <UsageBar label="Sites" used={sitesUsed} limit={org.site_limit} />
        <UsageBar label="Team seats" used={seatsUsed} limit={org.seat_limit} />
        <UsageBar label="Bandwidth" used={0} limit={org.bandwidth_gb} unit="GB" />
      </div>

      <div className="text-[13px] font-bold mb-3">Invoices</div>
      <Card className="p-0 overflow-hidden">
        {invoices.map((inv) => (
          <ListRow key={inv.number}>
            <span className="font-mono text-[12.5px] font-semibold flex-1 min-w-[100px]">
              {inv.number}
            </span>
            <span className="text-[12.5px] text-text-secondary flex-none">
              {new Date(inv.issued_at).toLocaleDateString()}
            </span>
            <span className="text-[13px] font-semibold flex-none w-[70px] text-right">
              ${(inv.amount_cents / 100).toFixed(2)}
            </span>
            <Badge status="Paid" />
          </ListRow>
        ))}
      </Card>
    </Shell>
  );
}
