import {
  getPlanDistribution,
  computeMrr,
  getAtRiskSubscriptions,
} from "@/lib/db/admin-queries"
import { StatsCard } from "@/components/dashboard/stats-card"
import { EmptyState } from "@/components/shared/empty-state"
import { PLAN_PRICES, getPlanLabel } from "@/lib/stripe/plans"
import { formatCurrency, formatDate } from "@/lib/utils"
import type { Plan } from "@/types"
import { DollarSign, TrendingUp, Gem, CreditCard, Download, ShieldCheck } from "lucide-react"

export const dynamic = "force-dynamic"

const STATUS_LABELS: Record<string, string> = {
  past_due: "Past due",
  unpaid: "Unpaid",
  incomplete: "Incomplete",
}

// Plan rows for the distribution table (in display order)
const PLAN_ROWS: { plan: Plan; amount: number; oneTime: boolean }[] = [
  { plan: "starter", amount: 0, oneTime: false },
  { plan: "pro", amount: PLAN_PRICES.pro?.amount ?? 29, oneTime: false },
  { plan: "landlord", amount: PLAN_PRICES.landlord?.amount ?? 59, oneTime: false },
  { plan: "lifetime", amount: PLAN_PRICES.lifetime?.amount ?? 199, oneTime: true },
]

export default async function AdminBillingPage() {
  const dist = await getPlanDistribution()
  const { mrr, arr, lifetimeRevenue } = computeMrr(dist)
  const atRisk = await getAtRiskSubscriptions()

  const paidCustomers = dist.pro + dist.landlord + dist.lifetime

  return (
    <div className="min-h-full">
      {/* Heading */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div>
          <h1 className="text-xl font-bold text-white">Billing</h1>
          <p className="text-sm text-white/40 mt-0.5">Revenue, plan mix, and subscription health</p>
        </div>
        <a
          href="/api/admin/export/billing"
          className="inline-flex items-center gap-2 rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white/80 transition hover:border-white/[0.16] hover:bg-white/[0.08] hover:text-white"
        >
          <Download className="h-4 w-4" />
          Export CSV
        </a>
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3 sm:gap-4 mb-6">
        <StatsCard label="MRR" value={formatCurrency(mrr)} sub="Recurring monthly" icon={DollarSign} variant="success" />
        <StatsCard label="ARR" value={formatCurrency(arr)} sub="Annualized run-rate" icon={TrendingUp} variant="success" />
        <StatsCard
          label="Lifetime Revenue"
          value={formatCurrency(lifetimeRevenue)}
          sub="One-time payments"
          icon={Gem}
          variant="warning"
        />
        <StatsCard label="Paid Customers" value={paidCustomers} sub="Active paid plans" icon={CreditCard} />
      </div>

      {/* Plan distribution table */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden mb-6">
        <div className="border-b border-white/[0.06] px-5 py-4">
          <h2 className="text-sm font-semibold text-white">Plan Distribution</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-white/[0.06] text-left text-[11px] uppercase tracking-wider text-white/40">
                <th className="px-5 py-3 font-medium">Plan</th>
                <th className="px-5 py-3 font-medium text-right">Subscribers</th>
                <th className="px-5 py-3 font-medium text-right">Unit Price</th>
                <th className="px-5 py-3 font-medium text-right">Monthly Contribution</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/[0.04]">
              {PLAN_ROWS.map(({ plan, amount, oneTime }) => {
                const count = dist[plan] ?? 0
                const isStarter = plan === "starter"
                return (
                  <tr key={plan} className="hover:bg-white/[0.02] transition-colors">
                    <td className="px-5 py-3.5">
                      <span className="font-medium text-white">{getPlanLabel(plan)}</span>
                      {oneTime && (
                        <span className="ml-2 rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[10px] font-semibold text-amber-400">
                          one-time
                        </span>
                      )}
                    </td>
                    <td className="px-5 py-3.5 text-right tabular-nums text-white/80">{count.toLocaleString()}</td>
                    <td className="px-5 py-3.5 text-right tabular-nums text-white/60">
                      {isStarter ? "—" : formatCurrency(amount)}
                      {oneTime && <span className="text-white/30"> /once</span>}
                    </td>
                    <td className="px-5 py-3.5 text-right tabular-nums">
                      {isStarter ? (
                        <span className="text-white/30">—</span>
                      ) : oneTime ? (
                        <span className="text-amber-400">
                          {formatCurrency(count * amount)}
                          <span className="text-white/30 text-xs"> one-time</span>
                        </span>
                      ) : (
                        <span className="font-semibold text-emerald-400">{formatCurrency(count * amount)}</span>
                      )}
                    </td>
                  </tr>
                )
              })}
            </tbody>
            <tfoot>
              <tr className="border-t border-white/[0.08] bg-white/[0.02]">
                <td className="px-5 py-3.5 font-semibold text-white">MRR Total</td>
                <td className="px-5 py-3.5 text-right tabular-nums text-white/60">{paidCustomers.toLocaleString()}</td>
                <td className="px-5 py-3.5" />
                <td className="px-5 py-3.5 text-right font-bold text-emerald-400 tabular-nums">{formatCurrency(mrr)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>

      {/* At-risk subscriptions table */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
        <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
          <h2 className="text-sm font-semibold text-white">At-risk Subscriptions</h2>
          {atRisk.length > 0 && (
            <span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-rose-500/20 px-1.5 text-[10px] font-bold text-rose-400">
              {atRisk.length}
            </span>
          )}
        </div>

        {atRisk.length === 0 ? (
          <EmptyState
            icon={ShieldCheck}
            title="No at-risk subscriptions"
            description="All paid subscriptions are in good standing."
            className="py-14"
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/[0.06] text-left text-[11px] uppercase tracking-wider text-white/40">
                  <th className="px-5 py-3 font-medium">Email</th>
                  <th className="px-5 py-3 font-medium">Plan</th>
                  <th className="px-5 py-3 font-medium">Status</th>
                  <th className="px-5 py-3 font-medium text-right">Expires</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/[0.04]">
                {atRisk.map((s) => (
                  <tr key={s.id} className="hover:bg-white/[0.02] transition-colors">
                    <td className="px-5 py-3.5">
                      <span className="font-medium text-white">{s.email}</span>
                      {s.full_name && <span className="ml-2 text-xs text-white/40">{s.full_name}</span>}
                    </td>
                    <td className="px-5 py-3.5 text-white/70">{getPlanLabel(s.plan as Plan)}</td>
                    <td className="px-5 py-3.5">
                      <span className="rounded-full border border-rose-500/20 bg-rose-500/10 px-2.5 py-1 text-[10px] font-semibold text-rose-400">
                        {STATUS_LABELS[s.subscription_status ?? ""] ?? s.subscription_status ?? "Unknown"}
                      </span>
                    </td>
                    <td className="px-5 py-3.5 text-right tabular-nums text-white/60">
                      {s.plan_expires_at ? formatDate(s.plan_expires_at) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  )
}
