"use client";

import { useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { api } from "@/lib/api/client";
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 { PageHeader } from "@/components/dashboard/page-header";

export default function NewCompetitionPage() {
  const router = useRouter();
  const params = useParams();
  const leagueId = params.leagueId as string;
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  return (
    <div className="space-y-6">
      <PageHeader title="New competition" description="Add a league season or cup" />
      <GlassCard>
        <form
          className="space-y-4 max-w-md"
          onSubmit={async (e) => {
            e.preventDefault();
            if (loading) return;
            const fd = new FormData(e.currentTarget);
            setLoading(true);
            setError(null);
            try {
              const comp = (await api.leagues.createCompetition(leagueId, {
                name: fd.get("name") as string,
                tournament_mode: fd.get("tournament_mode") as "league" | "cup",
              })) as { id: string };
              router.push(`/leagues/${leagueId}/competitions/${comp.id}`);
            } catch (err) {
              setError(err instanceof Error ? err.message : "Failed");
            } finally {
              setLoading(false);
            }
          }}
        >
          <div>
            <Label>Name</Label>
            <Input name="name" required className="mt-1" />
          </div>
          <div>
            <Label>Mode</Label>
            <select
              name="tournament_mode"
              className="mt-1 flex h-10 w-full rounded-lg border border-white/15 bg-white/5 px-3 text-sm"
            >
              <option value="league">League</option>
              <option value="cup">Cup</option>
            </select>
          </div>
          {error && <p className="text-sm text-red-400">{error}</p>}
          <Button type="submit" disabled={loading}>
            Create competition
          </Button>
        </form>
      </GlassCard>
    </div>
  );
}
