import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { createLeague } from "@/actions/leagues";
import { GlassCard } from "@/components/ui/glass-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Trophy, Plus } from "lucide-react";

export default async function LeaguesPage() {
  const supabase = await createClient();
  const { data: leagues } = await supabase
    .from("leagues")
    .select("*")
    .order("created_at", { ascending: false });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Leagues</h1>
          <p className="text-sm text-[var(--color-muted)]">
            Create and manage tournament leagues
          </p>
        </div>
      </div>

      <GlassCard title="New league">
        <form action={createLeague} className="flex flex-wrap items-end gap-4">
          <div className="min-w-[200px] flex-1">
            <Label htmlFor="name">Name</Label>
            <Input id="name" name="name" required className="mt-1" placeholder="Sunday League" />
          </div>
          <div className="min-w-[200px] flex-1">
            <Label htmlFor="description">Description</Label>
            <Input id="description" name="description" className="mt-1" placeholder="Optional" />
          </div>
          <Button type="submit">
            <Plus className="h-4 w-4" />
            Create league
          </Button>
        </form>
      </GlassCard>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {leagues?.map((league) => (
          <Link key={league.id} href={`/leagues/${league.id}`}>
            <GlassCard className="transition-colors hover:border-cyan-400/30">
              <div className="flex items-start gap-3">
                <div className="rounded-lg bg-cyan-500/15 p-2">
                  <Trophy className="h-5 w-5 text-cyan-400" />
                </div>
                <div>
                  <h3 className="font-semibold">{league.name}</h3>
                  <p className="mt-1 text-xs text-[var(--color-muted)] line-clamp-2">
                    {league.description || "No description"}
                  </p>
                </div>
              </div>
            </GlassCard>
          </Link>
        ))}
        {(!leagues || leagues.length === 0) && (
          <p className="col-span-full text-center text-[var(--color-muted)]">
            No leagues yet. Create your first league above.
          </p>
        )}
      </div>
    </div>
  );
}
