import { and, eq } from "drizzle-orm";
import { Zap } from "lucide-react";
import { getLocale, getTranslations } from "next-intl/server";
import { headers } from "next/headers";

import { PricingTable } from "@/components/billing/pricing-table";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { Button } from "@/components/ui/button";
import { Link } from "@/i18n/navigation";
import { auth } from "@/lib/auth";
import { resolveActiveOrgId } from "@/lib/auth-guards";
import { detectCurrencyFromHeaders, type Currency } from "@/lib/billing/currency";
import { getCurrencyCookie } from "@/lib/billing/currency-cookie";
import { ensureOrgSubscription } from "@/lib/billing/ensure-subscription";
import { db } from "@/lib/db";
import { member } from "@/lib/db/schema";

import { FaqSection } from "./faq-section";

export const metadata = {
  title: "Pricing — Eleva Speed",
  description: "Plans Free, Starter, Pro, Business and Enterprise for web performance monitoring.",
};

export default async function PricingPage() {
  const t = await getTranslations("Pricing");
  const tNav = await getTranslations("Marketing.nav");
  const locale = await getLocale();
  const requestHeaders = await headers();

  // Currency: cookie wins (user explicit choice). Otherwise infer from IP geo
  // (Vercel header) or Accept-Language. Fallback to EUR inside the detector.
  const cookieCurrency = await getCurrencyCookie();
  const currency: Currency = cookieCurrency ?? detectCurrencyFromHeaders(requestHeaders);

  // Try to detect signed-in user + their plan, but don't require auth.
  const session = await auth.api.getSession({ headers: requestHeaders }).catch(() => null);

  if (!session) {
    return <MarketingShell t={t} tNav={tNav} locale={locale} currency={currency} />;
  }

  // Resolve the active org (with fallback to earliest membership). If the
  // user genuinely has no org we fall back to the marketing layout — they
  // can still discover plans without sidebar chrome.
  const activeOrganizationId = await resolveActiveOrgId(session);
  if (!activeOrganizationId) {
    return (
      <MarketingShell t={t} tNav={tNav} locale={locale} currency={currency} currentPlan="free" />
    );
  }

  const [memberRow] = await db
    .select({ role: member.role })
    .from(member)
    .where(and(eq(member.organizationId, activeOrganizationId), eq(member.userId, session.user.id)))
    .limit(1);
  const role = (memberRow?.role ?? "member") as "owner" | "admin" | "member";

  const sub = await ensureOrgSubscription(activeOrganizationId);
  const currentPlan = sub.plan;

  return (
    <DashboardShell session={session} activeOrganizationId={activeOrganizationId} role={role}>
      <div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 md:gap-10 md:px-6">
        <PricingHeader t={t} />
        <PricingTable initialCurrency={currency} locale={locale} currentPlan={currentPlan} />
        <FaqSection />
        <EnterpriseCallout t={t} />
      </div>
    </DashboardShell>
  );
}

function PricingHeader({ t }: { t: Awaited<ReturnType<typeof getTranslations<"Pricing">>> }) {
  return (
    <header className="flex flex-col gap-4 text-center">
      <h1 className="text-4xl font-bold tracking-tight text-foreground">{t("title")}</h1>
      <p className="mx-auto max-w-2xl text-base text-muted-foreground">{t("subtitle")}</p>
    </header>
  );
}

function EnterpriseCallout({ t }: { t: Awaited<ReturnType<typeof getTranslations<"Pricing">>> }) {
  return (
    <section className="flex flex-col gap-2 text-center text-sm text-muted-foreground">
      <p>{t("enterpriseCallout")}</p>
      <p>
        <a href="mailto:bastien@elevaseo.com" className="text-primary hover:underline">
          bastien@elevaseo.com
        </a>
      </p>
    </section>
  );
}

function MarketingShell({
  t,
  tNav,
  locale,
  currency,
  currentPlan = null,
}: {
  t: Awaited<ReturnType<typeof getTranslations<"Pricing">>>;
  tNav: Awaited<ReturnType<typeof getTranslations<"Marketing.nav">>>;
  locale: string;
  currency: Currency;
  currentPlan?: string | null;
}) {
  return (
    <div className="flex min-h-svh flex-col">
      <MarketingHeader tNav={tNav} />
      <main className="mx-auto flex w-full max-w-6xl flex-1 flex-col gap-10 px-4 py-12">
        <PricingHeader t={t} />
        <PricingTable initialCurrency={currency} locale={locale} currentPlan={currentPlan} />
        <FaqSection />
        <EnterpriseCallout t={t} />
      </main>
      <MarketingFooter tNav={tNav} />
    </div>
  );
}

function MarketingHeader({
  tNav,
}: {
  tNav: Awaited<ReturnType<typeof getTranslations<"Marketing.nav">>>;
}) {
  return (
    <header className="sticky top-0 z-40 border-b border-border/60 bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60">
      <div className="mx-auto flex w-full max-w-6xl items-center justify-between gap-4 px-4 py-3">
        <Link
          href="/"
          className="flex items-center gap-2 font-semibold tracking-tight text-foreground"
        >
          <span className="flex size-7 items-center justify-center rounded-md bg-primary text-primary-foreground">
            <Zap className="size-4" />
          </span>
          <span>{tNav("brand")}</span>
        </Link>
        <nav className="hidden items-center gap-1 md:flex" aria-label={tNav("primaryNavLabel")}>
          <Button asChild variant="ghost" size="sm" aria-current="page">
            <Link href="/pricing">{tNav("pricing")}</Link>
          </Button>
        </nav>
        <div className="flex items-center gap-2">
          <Button asChild variant="ghost" size="sm">
            <Link href="/login">{tNav("signIn")}</Link>
          </Button>
          <Button asChild size="sm">
            <Link href="/signup">{tNav("signUp")}</Link>
          </Button>
        </div>
      </div>
    </header>
  );
}

function MarketingFooter({
  tNav,
}: {
  tNav: Awaited<ReturnType<typeof getTranslations<"Marketing.nav">>>;
}) {
  return (
    <footer className="mt-10 border-t border-border/60">
      <div className="mx-auto flex w-full max-w-6xl flex-col items-center justify-between gap-3 px-4 py-6 text-xs text-muted-foreground md:flex-row">
        <p>{tNav("footerTagline")}</p>
        <Link href="/login" className="hover:text-foreground hover:underline">
          {tNav("signIn")}
        </Link>
      </div>
    </footer>
  );
}
