import { Check, ExternalLink, ShieldCheck } from "lucide-react";
import { PageTitle } from "@/components/page-title";
import { StatusBadge } from "@/components/status-badge";
import { getSession } from "@/lib/auth/session";
import { db } from "@/lib/db";

function formatUsd(cents: number) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(cents / 100);
}

function intervalLabel(interval: "MONTHLY" | "ANNUAL" | "LIFETIME") {
  return interval === "ANNUAL" ? "Annual" : interval === "LIFETIME" ? "Lifetime promotional" : "Monthly";
}

export default async function BillingPage() {
  const session = await getSession();
  const [membership, plans] = await Promise.all([
    session ? db.organizationMember.findFirst({ where: { userId: session.userId }, include: { organization: { include: { subscription: { include: { plan: true } } } } } }) : null,
    db.plan.findMany({ where: { isActive: true }, orderBy: { siteLimit: "asc" } }),
  ]);
  const subscription = membership?.organization.subscription;
  const activePlan = subscription?.plan.code;
  const billedAmount = subscription ? (subscription.billingInterval === "ANNUAL" ? subscription.plan.annualPriceCents : subscription.plan.monthlyPriceCents) : 0;

  return <>
    <PageTitle title="Billing" description="Subscription entitlement is synchronized from WooCommerce Subscriptions through the secure bridge." />
    <section className="panel panel-pad mb-14"><div className="panel-head"><div><div className="panel-title">Current account</div><div className="panel-sub">{session?.email ?? "No WooCommerce customer connected"}</div></div>{subscription ? <StatusBadge tone={subscription.status === "ACTIVE" ? "success" : "warning"}>{subscription.status === "ACTIVE" ? "Active" : subscription.status.replaceAll("_", " ")}</StatusBadge> : <StatusBadge tone="neutral">Not connected</StatusBadge>}</div>{subscription ? <div className="grid grid-4"><div><div className="metric-label">Plan</div><div className="metric-value" style={{ fontSize: 18 }}>{subscription.plan.name}</div></div><div><div className="metric-label">Billing</div><div className="metric-value" style={{ fontSize: 18 }}>{formatUsd(billedAmount)} <span style={{ fontSize: 12, fontWeight: 500, color: "var(--text-tertiary)" }}>/{intervalLabel(subscription.billingInterval).toLowerCase()}</span></div></div><div><div className="metric-label">Licensed sites</div><div className="metric-value" style={{ fontSize: 18 }}>{subscription.plan.siteLimit}</div></div><div><div className="metric-label">Renews</div><div className="metric-value" style={{ fontSize: 18 }}>{subscription.currentPeriodEnd ? new Intl.DateTimeFormat("en", { month: "short", day: "numeric", year: "numeric" }).format(subscription.currentPeriodEnd) : "-"}</div></div></div> : <p className="field-help">Subscription details appear after the WooCommerce bridge confirms the customer entitlement.</p>}</section>
    <section className="billing-notice"><ShieldCheck size={19} /><div><strong>WooCommerce is the billing source of truth.</strong><span>Cards, invoices, renewals, cancellations, and failed-payment recovery stay in the WooCommerce store. The SaaS receives only signed entitlement updates.</span></div></section>
    <section className="plan-grid">{plans.map((plan) => <article className="plan-card" key={plan.code}><div><h2>{plan.name}</h2><p>{plan.siteLimit === 1 ? "For one WordPress business site." : `For teams managing up to ${plan.siteLimit} WordPress sites.`}</p></div><strong>{formatUsd(plan.monthlyPriceCents)} <span className="field-help">/ month</span></strong><p><b>{formatUsd(plan.annualPriceCents)} annually</b> · save about 35%</p><ul><li><Check size={15} /> {plan.siteLimit} licensed production {plan.siteLimit === 1 ? "site" : "sites"}</li><li><Check size={15} /> AI Chat with your own provider key</li><li><Check size={15} /> {plan.allowChatAnalytics ? "Central chat analytics" : "Site-level audit logs"}</li>{plan.allowMultiSiteJobs ? <li><Check size={15} /> Multi-site jobs</li> : null}{plan.allowWhiteLabel ? <li><Check size={15} /> White-label visitor chat</li> : null}{plan.clientSeatLimit > 0 ? <li><Check size={15} /> Up to {plan.clientSeatLimit} client seats</li> : null}</ul><span className={activePlan === plan.code ? "plan-state" : "field-help"}>{activePlan === plan.code ? "Current plan" : `${plan.trialDays}-day free trial · ${plan.refundWindowDays}-day guarantee subject to terms`}</span></article>)}</section>
    <section className="panel billing-panel"><div><h2>Subscription portal</h2><p>Once the WooCommerce storefront URL is configured, this action opens the customer account portal for subscription changes and invoices.</p></div><button className="button" disabled><ExternalLink size={16} /> Storefront not configured</button></section>
  </>;
}
