// src/components/billing/plan-grid.tsx — shared plan picker: monthly↔annual
// toggle, the 4-plan grid from PLANS, and the Enterprise contact card.
// Owns the interval state and reports it back through `onChoosePlan` — used by
// Settings → Billing and the /billing-locked paywall.
"use client";

import { CheckIcon, MailIcon } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { PLANS, type PlanDef, type PlanName } from "@/lib/billing/plans";
import { cn } from "@/lib/utils";

export const PLAN_LABELS: Record<PlanName, string> = {
  solo: "Solo",
  starter: "Starter",
  pro: "Pro",
  agency: "Agency",
};

const PLAN_DESC_KEYS = {
  solo: "planSoloDesc",
  starter: "planStarterDesc",
  pro: "planProDesc",
  agency: "planAgencyDesc",
} as const;

/** "$9.99" / "$49" — whole dollars drop the cents. */
function usd(cents: number) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
    maximumFractionDigits: 2,
  }).format(cents / 100);
}

export type PlanGridProps = {
  /** Fired with the chosen plan and the currently selected interval. */
  onChoosePlan: (plan: PlanDef, annual: boolean) => void;
  /** Only the org owner may act — everyone else sees the grid read-only. */
  isManager: boolean;
  /** Disables every CTA while any billing action is in flight. */
  busy: boolean;
  /** Plan whose CTA shows the pending spinner. */
  pendingPlan: PlanName | null;
  /** Subscribed plan — its card is highlighted with a disabled "current" CTA. */
  currentPlan?: PlanName | null;
};

export function PlanGrid({
  onChoosePlan,
  isManager,
  busy,
  pendingPlan,
  currentPlan = null,
}: PlanGridProps) {
  const t = useTranslations("Billing");
  const [annual, setAnnual] = useState(false);

  return (
    <>
      {/* ── Interval toggle ──────────────────────────────────────────── */}
      <div className="flex items-center justify-center gap-2">
        <div className="inline-flex items-center rounded-lg border bg-muted/40 p-1">
          <button
            type="button"
            onClick={() => setAnnual(false)}
            aria-pressed={!annual}
            className={cn(
              "rounded-md px-3.5 py-1.5 font-medium text-sm transition-colors",
              !annual
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {t("monthly")}
          </button>
          <button
            type="button"
            onClick={() => setAnnual(true)}
            aria-pressed={annual}
            className={cn(
              "flex items-center gap-2 rounded-md px-3.5 py-1.5 font-medium text-sm transition-colors",
              annual
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {t("annual")}
            <Badge
              variant="secondary"
              className="border-primary/30 bg-primary/15 text-primary"
            >
              {t("annualSavings")}
            </Badge>
          </button>
        </div>
      </div>

      {/* ── Plan grid ────────────────────────────────────────────────── */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        {PLANS.map((plan) => {
          const isCurrent = currentPlan === plan.name;
          const monthlyEquivalent = annual
            ? Math.round(plan.annualUsd / 12)
            : plan.monthlyUsd;
          return (
            <Card
              key={plan.name}
              className={cn(
                "flex flex-col",
                isCurrent && "border-primary/40 bg-primary/[0.03]",
              )}
            >
              <CardHeader>
                <CardTitle>{PLAN_LABELS[plan.name]}</CardTitle>
                <CardDescription>
                  {t(PLAN_DESC_KEYS[plan.name])}
                </CardDescription>
                <div className="flex items-baseline gap-1 pt-1">
                  <span className="font-heading font-semibold text-3xl tracking-tight">
                    {usd(monthlyEquivalent)}
                  </span>
                  <span className="text-muted-foreground text-sm">
                    {t("perMonth")}
                  </span>
                </div>
                {annual ? (
                  <p className="text-muted-foreground text-xs">
                    {t("billedAnnually", { price: usd(plan.annualUsd) })}
                  </p>
                ) : null}
              </CardHeader>
              <CardContent className="flex-1">
                <ul className="flex flex-col gap-2 text-sm">
                  <FeatureItem
                    label={t("featKeywords", { count: plan.limits.keywords })}
                  />
                  <FeatureItem
                    label={t("featProjects", { count: plan.limits.projects })}
                  />
                  <FeatureItem
                    label={t("featSeats", { count: plan.limits.seats })}
                  />
                  <FeatureItem
                    label={
                      plan.limits.integrations === -1
                        ? t("featIntegrationsUnlimited")
                        : t("featIntegrations", {
                            count: plan.limits.integrations,
                          })
                    }
                  />
                  <FeatureItem
                    label={t("featBacklinks", {
                      count: plan.limits.backlinkRows,
                    })}
                  />
                  <FeatureItem
                    label={t("featMcp", { count: plan.limits.mcpMonthly })}
                  />
                </ul>
              </CardContent>
              <CardFooter>
                {isCurrent ? (
                  <Button className="w-full" variant="outline" disabled>
                    {t("currentLabel")}
                  </Button>
                ) : (
                  <Button
                    className="w-full"
                    onClick={() => onChoosePlan(plan, annual)}
                    disabled={!isManager || busy}
                  >
                    {pendingPlan === plan.name ? "…" : t("choosePlan")}
                  </Button>
                )}
              </CardFooter>
            </Card>
          );
        })}
      </div>

      {/* ── Enterprise ───────────────────────────────────────────────── */}
      <Card>
        <CardHeader>
          <CardTitle>Enterprise</CardTitle>
          <CardDescription>{t("enterpriseDesc")}</CardDescription>
        </CardHeader>
        <CardFooter>
          <Button variant="outline" asChild>
            <a href="mailto:contact@elevaseo.com">
              <MailIcon className="size-4" />
              {t("contactUs")}
            </a>
          </Button>
        </CardFooter>
      </Card>
    </>
  );
}

function FeatureItem({ label }: { label: string }) {
  return (
    <li className="flex items-start gap-2">
      <CheckIcon className="mt-0.5 size-4 shrink-0 text-primary" />
      <span>{label}</span>
    </li>
  );
}
