"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { LeagueRules } from "@/lib/rules/schema";
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 { api } from "@/lib/api/client";

export function RulesForm({
  leagueId,
  initialRules,
}: {
  leagueId: string;
  initialRules: LeagueRules;
}) {
  const router = useRouter();
  const [rules, setRules] = useState(initialRules);
  const [loading, setLoading] = useState(false);

  async function handleSave() {
    setLoading(true);
    try {
      await api.leagues.saveRules(leagueId, rules);
      router.refresh();
    } finally {
      setLoading(false);
    }
  }

  return (
    <GlassCard title="Scoring & format">
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label>Points for win</Label>
          <Input
            type="number"
            value={rules.points_win}
            onChange={(e) =>
              setRules({ ...rules, points_win: Number(e.target.value) })
            }
            className="mt-1"
          />
        </div>
        <div>
          <Label>Points for draw</Label>
          <Input
            type="number"
            value={rules.points_draw}
            onChange={(e) =>
              setRules({ ...rules, points_draw: Number(e.target.value) })
            }
            className="mt-1"
          />
        </div>
        <div>
          <Label>Round robin</Label>
          <select
            value={rules.round_robin_format}
            onChange={(e) =>
              setRules({
                ...rules,
                round_robin_format: e.target.value as "single" | "double",
              })
            }
            className="mt-1 flex h-10 w-full rounded-lg border border-white/15 bg-white/5 px-3 text-sm"
          >
            <option value="single">Single</option>
            <option value="double">Double</option>
          </select>
        </div>
        <div>
          <Label>Auto-qualify (CL)</Label>
          <Input
            type="number"
            value={rules.auto_qualify_count}
            onChange={(e) =>
              setRules({
                ...rules,
                auto_qualify_count: Number(e.target.value),
              })
            }
            className="mt-1"
          />
        </div>
      </div>
      <Button className="mt-6" onClick={handleSave} disabled={loading}>
        Save new rules version
      </Button>
    </GlassCard>
  );
}
