import type { Metadata } from "next";
import Link from "next/link";
import { ListMusic } from "lucide-react";
import { requireAuth } from "@/lib/auth/guards";
import { subjectHasFeature } from "@/lib/billing/subscription";
import { prisma } from "@/lib/db";
import { PageHeader } from "@/components/app/page-header";
import { UpgradeGate } from "@/components/app/upgrade-gate";
import { SeriesCreateForm } from "@/components/app/series-create-form";
import { Card, CardContent } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";

export const metadata: Metadata = { title: "Series" };

export default async function SeriesPage() {
  const session = await requireAuth();
  const allowed = await subjectHasFeature(
    session.user.id,
    "series_generator",
    session.session.activeOrganizationId
  );

  if (!allowed) {
    return (
      <>
        <PageHeader title="Series generator" description="Plan a whole season at once." />
        <UpgradeGate
          title="Series generator is a Pro feature"
          description="Upgrade to Pro to plan entire seasons and batch-generate episodes."
          requiredPlan="Pro"
        />
      </>
    );
  }

  const series = await prisma.series.findMany({
    where: { userId: session.user.id },
    orderBy: { createdAt: "desc" },
    include: { _count: { select: { episodes: true } } },
  });

  return (
    <>
      <PageHeader
        title="Series generator"
        description="Plan a cohesive season, then generate each episode."
      />

      <SeriesCreateForm />

      <div className="mt-8 space-y-3">
        <h2 className="text-sm font-semibold text-muted-foreground">Your seasons</h2>
        {series.length > 0 ? (
          <div className="grid gap-3 sm:grid-cols-2">
            {series.map((s) => (
              <Link key={s.id} href={`/series/${s.id}`}>
                <Card className="transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                  <CardContent className="flex items-center gap-3 py-4">
                    <span className="flex h-11 w-11 items-center justify-center rounded-xl bg-brand/10 text-brand">
                      <ListMusic className="h-5 w-5" />
                    </span>
                    <div className="min-w-0">
                      <p className="truncate font-medium">{s.title}</p>
                      <p className="text-xs text-muted-foreground">
                        {s.plannedCount} planned · {s._count.episodes} generated
                      </p>
                    </div>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        ) : (
          <EmptyState
            icon={ListMusic}
            title="No seasons yet"
            description="Plan a cohesive season above, then generate each episode in a couple of clicks."
          />
        )}
      </div>
    </>
  );
}
