import Link from "next/link";
import { notFound } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { PageHeader } from "@/components/dashboard/page-header";
import { GlassCard } from "@/components/ui/glass-card";
import { Button } from "@/components/ui/button";

export default async function MasterLeagueDetailPage({
  params,
}: {
  params: Promise<{ leagueId: string }>;
}) {
  const { leagueId } = await params;
  const supabase = await createClient();

  const { data: league } = await supabase
    .from("leagues")
    .select("*, competitions(*)")
    .eq("id", leagueId)
    .single();

  if (!league) notFound();

  return (
    <div className="space-y-6">
      <PageHeader
        title={league.name}
        description={league.description ?? "League administration"}
        actions={
          <Button variant="outline" asChild>
            <Link href={`/leagues/${leagueId}/rules`}>Edit rules</Link>
          </Button>
        }
      />

      <GlassCard title="Competitions">
        <ul className="space-y-2">
          {league.competitions?.map(
            (c: { id: string; name: string; status: string; tournament_mode: string }) => (
              <li key={c.id}>
                <Link
                  href={`/leagues/${leagueId}/competitions/${c.id}`}
                  className="flex items-center justify-between rounded-lg border border-white/10 px-4 py-3 hover:bg-white/5"
                >
                  <span className="font-medium">{c.name}</span>
                  <span className="text-xs capitalize text-[var(--color-muted)]">
                    {c.tournament_mode} · {c.status}
                  </span>
                </Link>
              </li>
            )
          )}
          {(!league.competitions || league.competitions.length === 0) && (
            <p className="text-sm text-[var(--color-muted)]">No competitions yet</p>
          )}
        </ul>
        <Button className="mt-4" asChild>
          <Link href={`/master/leagues/${leagueId}/competitions/new`}>
            Add competition
          </Link>
        </Button>
      </GlassCard>
    </div>
  );
}
