import type { Metadata } from "next";

import { ActivePlansPanel } from "@/components/dashboard/active-plans-panel";
import { PageShell } from "@/components/layout/page-shell";
import { SupportActions } from "@/components/layout/support-actions";
import { GlassCard } from "@/components/shared/glass-card";
import { Badge } from "@/components/ui/badge";
import { ButtonLink } from "@/components/ui/button-link";
import { products } from "@/lib/data/catalog";
import { getSession } from "@/lib/auth/session";
import { getEntitlements } from "@/lib/db/store";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "My Plans",
  robots: { index: false, follow: false },
};

export default async function DashboardPlansPage() {
  const session = await getSession();
  const email = session?.email ?? "";
  const ids = email ? await getEntitlements(email) : [];
  const owned = products.filter((p) => ids.includes(p.id));
  const currentPlan = owned.find((p) => p.type === "program") ?? owned[0];

  return (
    <PageShell
      variant="app"
      title="My plans"
      description={
        currentPlan
          ? "Your active plan, coaching access, and upgrade options."
          : "Programs you own, downloads, and coaching access in one place."
      }
      breadcrumbs={[
        { label: "Dashboard", href: "/dashboard" },
        { label: "My Plans" },
      ]}
      actions={<SupportActions size="sm" />}
    >
      {currentPlan ? (
        <GlassCard className="mb-8 border-emerald-500/25 bg-emerald-500/5 p-6 sm:p-8">
          <div className="flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <Badge className="rounded-full bg-emerald-500/15 text-emerald-600 dark:text-emerald-400">
                Current plan
              </Badge>
              <h2 className="font-display mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
                {currentPlan.title}
              </h2>
              <p className="text-muted-foreground mt-2 max-w-2xl text-sm leading-relaxed">
                {currentPlan.description}
              </p>
            </div>
            <ButtonLink href="/programs" className="shrink-0 rounded-xl px-6">
              Update plan
            </ButtonLink>
          </div>
        </GlassCard>
      ) : null}
      <ActivePlansPanel plans={owned} />
    </PageShell>
  );
}
