"use client";

import { useEffect, useState, useTransition } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { AlertTriangle, CheckCircle2, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertTitle } from "@/components/ui/alert";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import { useLanguage } from "@/lib/i18n/context";
import { startCheckoutAction, openBillingPortalAction, getBillingStatusAction } from "@/actions/billing-actions";
import {
  PLANS,
  PURCHASABLE_PLANS,
  formatPlanPrice,
  annualEffectiveMonthly,
} from "@/config/plans";
import type { UserPlanAccess } from "@/lib/stripe/types";
import type { BillingInterval, PlanCode } from "@prisma/client";

const POLL_ATTEMPTS = 6;
const POLL_INTERVAL_MS = 2500;

function formatDate(date: Date | string, locale: "en" | "es"): string {
  const d = typeof date === "string" ? new Date(date) : date;
  return new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  }).format(d);
}

export function BillingPageContent({
  access: initialAccess,
  billingInterval,
  stripeConfigured,
}: {
  access: UserPlanAccess;
  billingInterval: BillingInterval | null;
  stripeConfigured: boolean;
}) {
  const { t, locale } = useLanguage();
  const b = t.billing;
  const router = useRouter();
  const searchParams = useSearchParams();
  const checkoutParam = searchParams.get("checkout");
  // From a pricing-page link (?plan=pro&interval=annual): preselects the
  // interval tab only — never triggers Checkout by itself, see ctaHref() in
  // src/components/sections/pricing.tsx.
  const requestedInterval = searchParams.get("interval");

  const [access, setAccess] = useState(initialAccess);
  const [interval, setInterval] = useState<BillingInterval>(
    billingInterval ?? (requestedInterval === "ANNUAL" ? "ANNUAL" : "MONTHLY"),
  );
  const [isPending, startTransition] = useTransition();
  const [pendingPlan, setPendingPlan] = useState<string | null>(null);
  const [attempts, setAttempts] = useState(0);
  // Derived, not stored: fully determined by checkoutParam, access, and how
  // many attempts have run.
  const polling = checkoutParam === "success" && !access.hasPaidAccess && attempts < POLL_ATTEMPTS;

  useEffect(() => {
    if (!polling) return;

    const timer = setTimeout(async () => {
      const latest = await getBillingStatusAction();
      if (latest) setAccess(latest);
      setAttempts((n) => n + 1);
    }, POLL_INTERVAL_MS);

    return () => clearTimeout(timer);
    // `access`/`attempts` (not just `polling`) are dependencies on purpose:
    // each poll's result changes them, which is what schedules the *next*
    // poll — collapsing this to only `[polling]` would stop after one
    // attempt, since the derived boolean itself often doesn't change
    // between individual polls.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [checkoutParam, access, attempts]);

  function dismissCheckoutParam() {
    router.replace("/dashboard/billing");
  }

  function handleChoosePlan(plan: PlanCode) {
    if (plan === "FREE") return;
    setPendingPlan(plan);
    startTransition(async () => {
      const result = await startCheckoutAction(plan, interval, locale);
      if (!result.success) {
        setPendingPlan(null);
        // startCheckoutAction redirects on success — this only runs on error.
        toast.error(result.error);
      }
    });
  }

  function handlePortal() {
    startTransition(async () => {
      const result = await openBillingPortalAction(locale);
      if (!result.success) {
        toast.error(result.error);
      }
    });
  }

  const planName = t.plans[PLANS[access.plan].translationKey].name;
  const statusKey = access.subscriptionStatus.toLowerCase().replace(/_(\w)/g, (_, c: string) =>
    c.toUpperCase(),
  ) as keyof typeof b.status;

  return (
    <div className="flex w-full max-w-[1500px] flex-col gap-4 pb-8">
      <div className="pt-0.5">
        <h1 className="text-[26px] font-semibold tracking-tight text-foreground sm:text-[28px]">{b.title}</h1>
        <p className="mt-1 max-w-2xl text-sm text-muted-foreground">{b.description}</p>
      </div>

        {checkoutParam === "success" && (
          <Alert className={cn(access.hasPaidAccess ? "border-emerald-500/40" : "border-brand-cyan/40")}>
            {access.hasPaidAccess ? (
              <CheckCircle2 className="text-emerald-500" />
            ) : polling ? (
              <Loader2 className="animate-spin text-brand-cyan" />
            ) : (
              <CheckCircle2 className="text-brand-cyan" />
            )}
            <AlertTitle>
              {access.hasPaidAccess
                ? b.checkout.activeNow.replace("{plan}", planName)
                : b.checkout.activationPending}
            </AlertTitle>
          </Alert>
        )}

        {checkoutParam === "canceled" && (
          <Alert>
            <AlertTitle>{b.checkout.canceled}</AlertTitle>
          </Alert>
        )}

        {!stripeConfigured && (
          <Alert variant="destructive">
            <AlertTriangle />
            <AlertTitle>{b.errors.notConfigured}</AlertTitle>
          </Alert>
        )}

        {access.subscriptionStatus === "PAST_DUE" && (
          <Alert variant="destructive">
            <AlertTriangle />
            <AlertTitle>{b.warnings.pastDue}</AlertTitle>
          </Alert>
        )}
        {access.subscriptionStatus === "UNPAID" && (
          <Alert variant="destructive">
            <AlertTriangle />
            <AlertTitle>{b.warnings.unpaid}</AlertTitle>
          </Alert>
        )}
        {access.subscriptionStatus === "INCOMPLETE" && (
          <Alert variant="destructive">
            <AlertTriangle />
            <AlertTitle>{b.warnings.incomplete}</AlertTitle>
          </Alert>
        )}
        {access.cancelAtPeriodEnd && access.currentPeriodEnd && (
          <Alert>
            <AlertTriangle />
            <AlertTitle>
              {b.warnings.cancelScheduled.replace("{date}", formatDate(access.currentPeriodEnd, locale))}
            </AlertTitle>
          </Alert>
        )}

      {/* Current plan card */}
      <Card className="rounded-2xl">
          <CardHeader>
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <CardTitle>{b.currentPlanCard.title}</CardTitle>
                <p className="mt-1 text-lg font-semibold text-foreground">
                  {b.currentPlanCard.currentPlan.replace("{plan}", planName)}
                </p>
              </div>
              <Badge
                variant="outline"
                className={cn(
                  "border-brand-cyan/30 bg-primary/10 text-primary",
                  (access.subscriptionStatus === "PAST_DUE" || access.subscriptionStatus === "UNPAID") &&
                    "border-destructive/40 bg-destructive/10 text-destructive",
                )}
              >
                {b.status[statusKey] ?? access.subscriptionStatus}
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="flex flex-col gap-2 text-sm text-muted-foreground">
            {access.plan === "FREE" ? (
              <p>{b.currentPlanCard.freeDescription}</p>
            ) : (
              <>
                <p>
                  {b.currentPlanCard.priceLabel}:{" "}
                  {formatPlanPrice(
                    interval === "ANNUAL"
                      ? PLANS[access.plan].priceAnnualDisplay
                      : PLANS[access.plan].priceMonthlyDisplay,
                    locale,
                  )}
                  {interval === "ANNUAL" ? b.planSelector.perYear : b.planSelector.perMonth}
                  {" · "}
                  {interval === "ANNUAL" ? b.currentPlanCard.interval.annual : b.currentPlanCard.interval.monthly}
                </p>
                {access.currentPeriodEnd && !access.cancelAtPeriodEnd && (
                  <p>{b.currentPlanCard.renewsOn.replace("{date}", formatDate(access.currentPeriodEnd, locale))}</p>
                )}
                {access.currentPeriodEnd && access.cancelAtPeriodEnd && (
                  <p>{b.currentPlanCard.endsOn.replace("{date}", formatDate(access.currentPeriodEnd, locale))}</p>
                )}
              </>
            )}
          </CardContent>
        </Card>

        {/* Plan selector */}
        <div className="flex flex-col gap-4">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-lg font-semibold text-foreground">{b.planSelector.title}</h2>
            <Tabs value={interval} onValueChange={(v) => setInterval(v as BillingInterval)}>
              <TabsList>
                <TabsTrigger value="MONTHLY">{b.planSelector.monthly}</TabsTrigger>
                <TabsTrigger value="ANNUAL">{b.planSelector.annual}</TabsTrigger>
              </TabsList>
            </Tabs>
          </div>

          <div className="grid gap-4 md:grid-cols-3">
            {(["FREE", ...PURCHASABLE_PLANS] as PlanCode[]).map((planCode) => {
              const plan = PLANS[planCode];
              const isCurrent = access.plan === planCode && (planCode === "FREE" || access.hasPaidAccess);
              const price = interval === "ANNUAL" ? plan.priceAnnualDisplay : plan.priceMonthlyDisplay;

              return (
                <Card
                  key={planCode}
                  className={cn("rounded-2xl", plan.recommended && "ring-2 ring-brand-cyan/50")}
                >
                  <CardHeader>
                    <div className="flex items-center justify-between gap-2">
                      <CardTitle>{t.plans[plan.translationKey].name}</CardTitle>
                      {plan.recommended && (
                        <Badge className="bg-gradient-to-r from-brand-cyan to-brand-blue text-background">
                          {b.planSelector.recommendedBadge}
                        </Badge>
                      )}
                    </div>
                    <p className="text-sm text-muted-foreground">{t.plans[plan.translationKey].description}</p>
                  </CardHeader>
                  <CardContent className="flex flex-col gap-4">
                    <div className="flex items-baseline gap-1.5">
                      <span className="text-3xl font-semibold tracking-tight text-foreground">
                        {formatPlanPrice(price, locale)}
                      </span>
                      {planCode !== "FREE" && (
                        <span className="text-sm text-muted-foreground">
                          {interval === "ANNUAL" ? b.planSelector.perYear : b.planSelector.perMonth}
                        </span>
                      )}
                    </div>
                    {planCode !== "FREE" && interval === "ANNUAL" && (
                      <p className="text-xs text-muted-foreground">
                        {b.planSelector.effectiveMonthly.replace(
                          "{price}",
                          formatPlanPrice(annualEffectiveMonthly(planCode), locale),
                        )}
                      </p>
                    )}

                    {isCurrent ? (
                      <Badge variant="outline" className="w-fit border-brand-cyan/30 bg-primary/10 text-primary">
                        {b.planSelector.currentPlanBadge}
                      </Badge>
                    ) : planCode === "FREE" ? (
                      access.hasPaidAccess ? (
                        <Button variant="outline" size="sm" onClick={handlePortal} disabled={isPending}>
                          {b.planSelector.manage}
                        </Button>
                      ) : null
                    ) : access.hasPaidAccess ? (
                      <Button variant="outline" size="sm" onClick={handlePortal} disabled={isPending}>
                        {b.planSelector.manage}
                      </Button>
                    ) : (
                      <Button
                        size="sm"
                        disabled={isPending || !stripeConfigured}
                        onClick={() => handleChoosePlan(planCode)}
                      >
                        {isPending && pendingPlan === planCode ? (
                          <Loader2 className="size-4 animate-spin" />
                        ) : null}
                        {b.planSelector.choosePlan}
                      </Button>
                    )}
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>

        {/* Subscription details + actions */}
        <div className="grid gap-4 lg:grid-cols-2">
          <Card className="rounded-2xl">
            <CardHeader>
              <CardTitle>{b.details.title}</CardTitle>
            </CardHeader>
            <CardContent className="flex flex-col gap-2 text-sm">
              <div className="flex justify-between border-b border-border py-2">
                <span className="text-muted-foreground">{b.details.status}</span>
                <span className="text-foreground">{b.status[statusKey] ?? access.subscriptionStatus}</span>
              </div>
              <div className="flex justify-between border-b border-border py-2">
                <span className="text-muted-foreground">{b.details.billingInterval}</span>
                <span className="text-foreground">
                  {access.plan === "FREE"
                    ? b.details.notAvailable
                    : interval === "ANNUAL"
                      ? b.currentPlanCard.interval.annual
                      : b.currentPlanCard.interval.monthly}
                </span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-muted-foreground">{b.details.renewalDate}</span>
                <span className="text-foreground">
                  {access.currentPeriodEnd ? formatDate(access.currentPeriodEnd, locale) : b.details.notAvailable}
                </span>
              </div>
            </CardContent>
          </Card>

          <Card className="rounded-2xl">
            <CardHeader>
              <CardTitle>{b.actions.manageBilling}</CardTitle>
            </CardHeader>
            <CardContent className="flex flex-wrap gap-3">
              <Button variant="outline" onClick={handlePortal} disabled={isPending || !access.hasPaidAccess}>
                {b.actions.manageBilling}
              </Button>
              <Button variant="outline" onClick={handlePortal} disabled={isPending || !access.hasPaidAccess}>
                {b.actions.viewInvoices}
              </Button>
              {(access.subscriptionStatus === "PAST_DUE" || access.subscriptionStatus === "UNPAID") && (
                <Button onClick={handlePortal} disabled={isPending}>
                  {b.actions.resolvePaymentIssue}
                </Button>
              )}
            </CardContent>
          </Card>
        </div>

      {(checkoutParam === "success" || checkoutParam === "canceled") && (
        <Button variant="ghost" size="sm" className="w-fit" onClick={dismissCheckoutParam}>
          ×
        </Button>
      )}
    </div>
  );
}
