"use client" import { useState } from "react" interface ScheduleGeneratorProps { tournamentId: number teamCount: number existingRounds?: number } export function ScheduleGenerator({ tournamentId, teamCount, existingRounds }: ScheduleGeneratorProps) { const [isGenerating, setIsGenerating] = useState(false) const [error, setError] = useState("") const [result, setResult] = useState<{ roundsCreated: number matchupsCreated: number } | null>(null) const [showOverwriteConfirm, setShowOverwriteConfirm] = useState(false) const handleGenerate = async () => { setError("") setResult(null) setIsGenerating(true) setShowOverwriteConfirm(false) try { const response = await fetch(`/api/tournaments/${tournamentId}/schedule`, { method: "POST", }) // Check response status first before parsing JSON if (!response.ok) { try { const data = await response.json() setError(data.error || "Failed to generate schedule") } catch { setError(`Failed to generate schedule: ${response.status} ${response.statusText}`) } setIsGenerating(false) return } const data = await response.json() setResult({ roundsCreated: data.roundsCreated, matchupsCreated: data.matchupsCreated, }) setIsGenerating(false) // Reload to show the schedule setTimeout(() => { window.location.reload() }, 1500) } catch { setError("An error occurred. Please try again.") setIsGenerating(false) } } const handleGenerateClick = () => { if (existingRounds && existingRounds > 0) { setShowOverwriteConfirm(true) } else { handleGenerate() } } const handleDelete = async () => { setError("") setIsGenerating(true) try { const response = await fetch(`/api/tournaments/${tournamentId}/schedule`, { method: "DELETE", }) if (!response.ok) { try { const data = await response.json() setError(data.error || "Failed to delete schedule") } catch { setError(`Failed to delete schedule: ${response.status} ${response.statusText}`) } setIsGenerating(false) return } window.location.reload() } catch { setError("An error occurred. Please try again.") setIsGenerating(false) } } const expectedRounds = teamCount % 2 === 0 ? teamCount - 1 : teamCount const expectedMatchups = (teamCount * (teamCount - 1)) / 2 return (
{error && (
{error}
)} {result && (
Generated {result.roundsCreated} rounds with {result.matchupsCreated} matchups!
)}

Generate a round-robin schedule for {teamCount} teams.

This will create {expectedRounds} rounds with {expectedMatchups} total matchups. Each team plays every other team exactly once.

{/* Overwrite Confirmation */} {showOverwriteConfirm && (

Overwrite existing schedule?

A schedule with {existingRounds} round(s) already exists. This will delete the existing schedule and create a new one.

)}
) }