// src/components/billing/billing-locked.tsx — /billing-locked client UI.
// Trial-expired paywall: headline + the shared PlanGrid (Checkout via the
// Better Auth Stripe plugin). Non-owners can't act — they see a prominent
// hint to ask the org owner. A sign-out link keeps stuck users from being
// trapped.
"use client";

import { LockIcon } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "sonner";
import { PlanGrid } from "@/components/billing/plan-grid";
import { authClient } from "@/lib/auth-client";
import type { PlanDef, PlanName } from "@/lib/billing/plans";

export function BillingLocked({
  orgId,
  isManager,
}: {
  orgId: string;
  isManager: boolean;
}) {
  const t = useTranslations("Billing");
  const tNav = useTranslations("Nav");
  const [pendingPlan, setPendingPlan] = useState<PlanName | null>(null);

  async function choosePlan(plan: PlanDef, annual: boolean) {
    setPendingPlan(plan.name);
    try {
      const res = await authClient.subscription.upgrade({
        plan: plan.name,
        annual,
        referenceId: orgId,
        customerType: "organization",
        successUrl: "/keywords/reservoir",
        cancelUrl: "/billing-locked",
      });
      if (res.error) {
        toast.error(t("checkoutError"));
      }
    } catch {
      toast.error(t("checkoutError"));
    } finally {
      setPendingPlan(null);
    }
  }

  async function signOut() {
    await authClient.signOut();
    window.location.href = "/login";
  }

  return (
    <div className="flex w-full max-w-3xl flex-col gap-6">
      {/* ── Headline ─────────────────────────────────────────────────── */}
      <div className="flex flex-col items-center gap-2 text-center">
        <div className="flex size-12 items-center justify-center rounded-full bg-primary/10">
          <LockIcon className="size-6 text-primary" />
        </div>
        <h1 className="font-heading font-semibold text-3xl tracking-tight">
          {t("lockedTitle")}
        </h1>
        <p className="text-muted-foreground">{t("lockedSubtitle")}</p>
        {!isManager ? (
          <p className="mt-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 font-medium text-amber-600 text-sm dark:text-amber-400">
            {t("lockedMemberHint")}
          </p>
        ) : null}
      </div>

      {/* ── Plans (toggle + grid + Enterprise) ───────────────────────── */}
      <PlanGrid
        onChoosePlan={choosePlan}
        isManager={isManager}
        busy={pendingPlan !== null}
        pendingPlan={pendingPlan}
      />

      {/* ── Escape hatch ─────────────────────────────────────────────── */}
      <div className="text-center">
        <button
          type="button"
          onClick={signOut}
          className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
        >
          {tNav("signOut")}
        </button>
      </div>
    </div>
  );
}
