// src/components/admin/billing-overview.tsx — God-Mode Financial Supervision
// (client). KPI cards (subs by status + a clearly-labelled MRR estimate), then
// a tenant billing table (org → customer → plan/status → period end → trial)
// with a status filter + name search driving the URL searchParams; the server
// page re-queries. Each row links to the org detail page (where the Stripe
// supervision actions live).
"use client";

import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState, useTransition } from "react";
import { BillingStatusBadge } from "@/components/admin/orgs-table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type {
  BillingStatusBucket,
  ListBillingOverviewResult,
} from "@/lib/admin/billing-queries";

function fmtDate(d: Date | string | null): string {
  return d ? new Date(d).toLocaleDateString() : "—";
}

function fmtUsd(cents: number): string {
  return (cents / 100).toLocaleString(undefined, {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: 0,
  });
}

const FILTERS: (BillingStatusBucket | "all")[] = [
  "all",
  "active",
  "trialing",
  "past_due",
  "canceled",
  "none",
];

/** Map a coarse bucket → the BillingStatusBadge's tri-state status. */
function badgeStatus(
  bucket: BillingStatusBucket,
): "active" | "trialing" | "expired" {
  if (bucket === "active") return "active";
  if (bucket === "trialing") return "trialing";
  return "expired";
}

export function AdminBillingOverview({
  result,
}: {
  result: ListBillingOverviewResult;
}) {
  const t = useTranslations("SuperAdmin");
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [search, setSearch] = useState(result.search);
  const [pending, startTransition] = useTransition();

  const { rows, kpis, total, limit, offset, status } = result;
  const hasPrev = offset > 0;
  const hasNext = offset + limit < total;

  function go(params: Record<string, string | null>) {
    const next = new URLSearchParams(searchParams.toString());
    for (const [k, v] of Object.entries(params)) {
      if (v === null || v === "") next.delete(k);
      else next.set(k, v);
    }
    startTransition(() => router.push(`${pathname}?${next.toString()}`));
  }

  function submitSearch(e: React.FormEvent) {
    e.preventDefault();
    go({ q: search.trim() || null, offset: null });
  }

  const kpiCards: {
    key: "active" | "trialing" | "past_due" | "canceled";
    count: number;
  }[] = [
    { key: "active", count: kpis.counts.active },
    { key: "trialing", count: kpis.counts.trialing },
    { key: "past_due", count: kpis.counts.past_due },
    { key: "canceled", count: kpis.counts.canceled },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-semibold text-xl">{t("billingTitle")}</h1>
        <p className="text-muted-foreground text-sm">{t("billingSubtitle")}</p>
        {!result.stripeConfigured ? (
          <Badge variant="destructive" className="mt-2">
            {t("billingStripeOff")}
          </Badge>
        ) : null}
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-5">
        {kpiCards.map((c) => (
          <Card key={c.key}>
            <CardHeader className="pb-2">
              <CardDescription>{t(`billingKpi_${c.key}`)}</CardDescription>
              <CardTitle className="text-2xl tabular-nums">{c.count}</CardTitle>
            </CardHeader>
          </Card>
        ))}
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>{t("billingKpiMrr")}</CardDescription>
            <CardTitle className="text-2xl tabular-nums">
              {fmtUsd(kpis.mrrEstimateCents)}
            </CardTitle>
            <CardContent className="px-0 pt-1">
              <span className="text-[10px] text-muted-foreground uppercase tracking-wide">
                {t("billingKpiMrrEstimate")}
              </span>
            </CardContent>
          </CardHeader>
        </Card>
      </div>

      {/* Filter + search */}
      <div className="flex flex-wrap items-center gap-2">
        <form onSubmit={submitSearch} className="flex flex-1 gap-2">
          <Input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder={t("billingSearchPlaceholder")}
            className="max-w-xs"
          />
          <Button type="submit" variant="secondary" disabled={pending}>
            {t("orgsSearch")}
          </Button>
        </form>
        <Select
          value={status}
          onValueChange={(v) =>
            go({ status: v === "all" ? null : v, offset: null })
          }
        >
          <SelectTrigger className="w-44">
            <SelectValue />
          </SelectTrigger>
          <SelectContent position="popper">
            {FILTERS.map((f) => (
              <SelectItem key={f} value={f}>
                {t(`billingFilter_${f}`)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Tenant billing table */}
      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t("orgsColName")}</TableHead>
              <TableHead>{t("billingColCustomer")}</TableHead>
              <TableHead>{t("orgsColBilling")}</TableHead>
              <TableHead className="text-right">
                {t("billingColSeats")}
              </TableHead>
              <TableHead>{t("billingColPeriodEnd")}</TableHead>
              <TableHead>{t("orgsColTrialEnd")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className="text-center text-muted-foreground"
                >
                  {t("orgsEmpty")}
                </TableCell>
              </TableRow>
            ) : (
              rows.map((row) => (
                <TableRow key={row.orgId}>
                  <TableCell>
                    <Link
                      href={`/admin/orgs/${row.orgId}`}
                      className="font-medium hover:underline"
                    >
                      {row.orgName}
                    </Link>
                  </TableCell>
                  <TableCell className="font-mono text-muted-foreground text-xs">
                    {row.stripeCustomerId ?? "—"}
                  </TableCell>
                  <TableCell>
                    <BillingStatusBadge
                      status={badgeStatus(row.status)}
                      plan={row.plan}
                    />
                  </TableCell>
                  <TableCell className="text-right tabular-nums">
                    {row.seats ?? "—"}
                  </TableCell>
                  <TableCell className="text-muted-foreground text-sm">
                    {fmtDate(row.periodEnd)}
                  </TableCell>
                  <TableCell className="text-muted-foreground text-sm">
                    {fmtDate(row.trialEndsAt)}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <div className="flex items-center justify-between">
        <span className="text-muted-foreground text-sm">
          {t("orgsTotal", { count: total })}
        </span>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={!hasPrev || pending}
            onClick={() => go({ offset: String(Math.max(0, offset - limit)) })}
          >
            {t("prev")}
          </Button>
          <Button
            variant="outline"
            size="sm"
            disabled={!hasNext || pending}
            onClick={() => go({ offset: String(offset + limit) })}
          >
            {t("next")}
          </Button>
        </div>
      </div>
    </div>
  );
}
