import { redirect } from "next/navigation";
import { auth } from "@/app/(auth)/auth";
import { PricingClient } from "@/components/pricing-client";
import { LIMITS, type Tier } from "@/lib/subscription/config";
import { ensureSubscription } from "@/lib/subscription/service";

export const dynamic = "force-dynamic";

export default async function PricingPage({
  searchParams,
}: {
  searchParams: Promise<{ upgraded?: string; canceled?: string }>;
}) {
  const session = await auth();
  if (!session?.user) {
    redirect("/api/auth/guest?redirectUrl=%2Fpricing");
  }

  const sub = await ensureSubscription(session.user.id);
  const params = await searchParams;

  return (
    <div className="mx-auto flex min-h-dvh max-w-5xl flex-col gap-8 px-6 py-12">
      <div className="flex flex-col gap-2">
        <a className="text-muted-foreground text-sm hover:text-foreground" href="/">
          ← Back to chat
        </a>
        <h1 className="font-semibold text-3xl">Pricing</h1>
        <p className="text-muted-foreground text-sm">
          You are currently on the <strong>{sub.tier}</strong> tier.
          {params.upgraded === "1" && (
            <span className="ml-2 text-green-600">
              Welcome to Pro — limits updated.
            </span>
          )}
          {params.canceled === "1" && (
            <span className="ml-2 text-amber-600">Checkout canceled.</span>
          )}
        </p>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Plan
          currentTier={sub.tier as Tier}
          description="Try the chatbot with a small daily quota."
          price="Free"
          tier="free"
        />
        <Plan
          currentTier={sub.tier as Tier}
          description="Higher daily quotas for serious use."
          price="$10 / month"
          tier="pro"
        />
      </div>

      <PricingClient currentTier={sub.tier as Tier} />
    </div>
  );
}

function Plan({
  tier,
  price,
  description,
  currentTier,
}: {
  tier: Tier;
  price: string;
  description: string;
  currentTier: Tier;
}) {
  const tierLimits = LIMITS[tier];
  const isCurrent = tier === currentTier;
  return (
    <div className="flex flex-col gap-4 rounded-2xl border border-border/40 bg-card p-6 shadow-sm">
      <div>
        <div className="flex items-baseline justify-between">
          <div className="font-medium text-lg capitalize">{tier}</div>
          {isCurrent && (
            <span className="rounded-full bg-muted px-2 py-0.5 text-muted-foreground text-xs">
              Current
            </span>
          )}
        </div>
        <div className="font-semibold text-2xl">{price}</div>
        <p className="mt-1 text-muted-foreground text-sm">{description}</p>
      </div>
      <ul className="flex flex-col gap-1.5 text-sm">
        <li>• {tierLimits.chat_message} messages / day</li>
        <li>• {tierLimits.tool_call} tool calls / day</li>
        <li>• All available models</li>
      </ul>
    </div>
  );
}
