import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, tierDefinitions, tierEnum, userUsage, userBillingDetails, eq, and } from "@epicure/db";
import { getRecipeCount, getStorageUsedMb, UNLIMITED } from "@/lib/tiers";
import { BillingPlanCards } from "@/components/settings/billing-plan-cards";
import { ManageBillingButton } from "@/components/settings/manage-billing-button";
import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
import { BillingDetailsForm } from "@/components/settings/billing-details-form";
import { Badge } from "@/components/ui/badge";
import { FEATURE_DEFINITIONS } from "@/lib/feature-flags";
import { Sparkles } from "lucide-react";

export const metadata: Metadata = {};

const TIER_NAMES: Record<string, string> = { free: "Free", pro: "Pro", family: "Family" };

function describeLimit(n: number, unit: string): string {
  return n === UNLIMITED ? `Unlimited ${unit}` : `${n} ${unit}`;
}

export default async function BillingPage({ searchParams }: { searchParams: Promise<{ checkout?: string; upgrade?: string }> }) {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;
  const { checkout, upgrade } = await searchParams;
  const upgradeFeature = FEATURE_DEFINITIONS.find((f) => f.key === upgrade);

  const currentMonth = new Date().toISOString().slice(0, 7);

  const [dbUser, allTierDefs, usage, recipeCount, storageUsedMb, billingDetails] = await Promise.all([
    db.query.users.findFirst({
      where: eq(users.id, session.user.id),
      columns: { tier: true, subscriptionStatus: true, currentPeriodEnd: true, stripeCustomerId: true },
    }),
    db.select().from(tierDefinitions),
    db.query.userUsage.findFirst({ where: and(eq(userUsage.userId, session.user.id), eq(userUsage.month, currentMonth)) }),
    getRecipeCount(session.user.id),
    getStorageUsedMb(session.user.id),
    db.query.userBillingDetails.findFirst({ where: eq(userBillingDetails.userId, session.user.id) }),
  ]);

  const currentTier = dbUser?.tier ?? "free";
  const currentTierDef = allTierDefs.find((t) => t.tier === currentTier);

  const asLimit = (n: number | undefined) => (n === undefined || n === UNLIMITED ? null : n);
  const usageMetrics = [
    { label: "AI calls", used: usage?.aiCallsUsed ?? 0, limit: asLimit(currentTierDef?.aiCallsPerMonth), unlimitedLabel: "Unlimited" },
    { label: "Recipes created", used: recipeCount, limit: asLimit(currentTierDef?.maxRecipes), unlimitedLabel: "Unlimited" },
    { label: "Storage", used: storageUsedMb, limit: asLimit(currentTierDef?.storageMb), unit: " MB", unlimitedLabel: "Unlimited" },
  ];

  const plans = tierEnum.enumValues.map((tier) => {
    const def = allTierDefs.find((t) => t.tier === tier);
    return {
      tier,
      name: TIER_NAMES[tier] ?? tier,
      monthlyPrice: tier === "free" ? "€0" : "Contact for pricing",
      yearlyPrice: null,
      features: def
        ? [
            describeLimit(def.maxRecipes, "recipes"),
            describeLimit(def.aiCallsPerMonth, "AI calls/month"),
            describeLimit(def.storageMb, "MB storage"),
          ]
        : [],
      purchasable: tier === "free" || !!(def?.stripePriceIdMonthly),
    };
  });

  return (
    <div className="space-y-8">
      {upgradeFeature && (
        <div className="flex items-start gap-3 rounded-lg border border-primary/40 bg-primary/5 p-4 text-sm">
          <Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
          <p>
            Upgrading unlocks <strong>{upgradeFeature.label}</strong> — {upgradeFeature.description}
          </p>
        </div>
      )}
      {checkout === "success" && (
        <div className="rounded-lg border border-primary/40 bg-primary/5 p-4 text-sm">
          Payment received — your plan updates within a few seconds as Stripe confirms it. Refresh if it doesn&apos;t show up right away.
        </div>
      )}
      {checkout === "canceled" && (
        <div className="rounded-lg border p-4 text-sm text-muted-foreground">
          Checkout canceled — no changes made.
        </div>
      )}

      <section className="rounded-xl border p-6 space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="font-semibold text-lg">Current plan: {TIER_NAMES[currentTier] ?? currentTier}</h2>
            {dbUser?.currentPeriodEnd && (
              <p className="text-sm text-muted-foreground mt-1">
                Renews {dbUser.currentPeriodEnd.toLocaleDateString()}
              </p>
            )}
          </div>
          {dbUser?.subscriptionStatus === "past_due" && (
            <Badge variant="destructive">Payment failed — update your card</Badge>
          )}
        </div>
        {dbUser?.stripeCustomerId && <ManageBillingButton />}
      </section>

      <section className="rounded-xl border p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-lg">Usage this month</h2>
          <p className="text-sm text-muted-foreground mt-1">AI calls reset monthly. Recipes and storage are lifetime totals.</p>
        </div>
        <UsageQuotaSection metrics={usageMetrics} />
      </section>

      <section className="rounded-xl border p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-lg">Billing details</h2>
          <p className="text-sm text-muted-foreground mt-1">Used on invoices. Full name is required; address and phone are optional.</p>
        </div>
        <BillingDetailsForm initialDetails={billingDetails ?? null} />
      </section>

      <section className="space-y-4">
        <h2 className="font-semibold text-lg">Plans</h2>
        <BillingPlanCards currentTier={currentTier} plans={plans} />
      </section>
    </div>
  );
}
