"use client" import { useState } from "react" import { useRouter } from "next/navigation" import type { Player, Match } from "@prisma/client" interface MatchEditorProps { tournamentId: number players: Player[] matches: Match[] targetScore: number | null allowTies: boolean // Optional pre-filled player IDs from URL params prefilledP1?: number prefilledP2?: number prefilledP3?: number prefilledP4?: number prefilledRound?: number } interface MatchData { team1P1Id: number | null team1P2Id: number | null team2P1Id: number | null team2P2Id: number | null team1Score: number team2Score: number round: number table: string isCasual: boolean } export default function MatchEditor({ tournamentId, players, targetScore, allowTies, prefilledP1, prefilledP2, prefilledP3, prefilledP4, prefilledRound, }: MatchEditorProps) { const router = useRouter() // Check if players are prefilled from URL params const hasPrefilledPlayers = prefilledP1 && prefilledP2 && prefilledP3 && prefilledP4; const [formData, setFormData] = useState({ team1P1Id: hasPrefilledPlayers ? prefilledP1 : null, team1P2Id: hasPrefilledPlayers ? prefilledP2 : null, team2P1Id: hasPrefilledPlayers ? prefilledP3 : null, team2P2Id: hasPrefilledPlayers ? prefilledP4 : null, team1Score: 0, team2Score: 0, round: prefilledRound || 1, table: "Clubs", isCasual: false, }) const [error, setError] = useState("") const [success, setSuccess] = useState("") const [isLoading, setIsLoading] = useState(false) const tables = ["Clubs", "Hearts", "Diamonds", "Spades", "Stars"] const handleChange = (e: React.ChangeEvent) => { const { name, value, type } = e.target const checked = (e.target as HTMLInputElement).checked setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : name.includes("Id") ? (value ? parseInt(value) : null) : name === "round" ? parseInt(value) : name === "team1Score" || name === "team2Score" ? parseInt(value) : value, })) } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setError("") setSuccess("") // Validate that all players are selected if (!formData.team1P1Id || !formData.team1P2Id || !formData.team2P1Id || !formData.team2P2Id) { setError("Please select all 4 players") return } // Validate that players are unique const playerIds = [formData.team1P1Id, formData.team1P2Id, formData.team2P1Id, formData.team2P2Id] if (new Set(playerIds).size !== 4) { setError("All players must be unique") return } // Validate scores (at least one team must have points) if (formData.team1Score === 0 && formData.team2Score === 0) { setError("At least one team must have points") return } // Validate target score if provided if (targetScore) { const team1ReachedTarget = formData.team1Score >= targetScore; const team2ReachedTarget = formData.team2Score >= targetScore; // Check if one team reached the target if (!team1ReachedTarget && !team2ReachedTarget) { setError(`Scores must reach the target score of ${targetScore}`) return } // Check if both teams reached the target (invalid unless ties are allowed and it's a tie) if (team1ReachedTarget && team2ReachedTarget && formData.team1Score !== formData.team2Score) { setError(`Only one team can reach the target score of ${targetScore}`) return } } // Validate ties if (!allowTies && formData.team1Score === formData.team2Score) { setError("Ties are not allowed in this tournament") return } setIsLoading(true) try { const response = await fetch("/api/matches", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ eventId: tournamentId, team1P1Id: formData.team1P1Id, team1P2Id: formData.team1P2Id, team2P1Id: formData.team2P1Id, team2P2Id: formData.team2P2Id, team1Score: formData.team1Score, team2Score: formData.team2Score, round: formData.round, table: formData.table, isCasual: formData.isCasual, }), }) if (!response.ok) { try { const data = await response.json() setError(data.error || "Failed to record match") } catch { setError(`Failed to record match: ${response.status} ${response.statusText}`) } setIsLoading(false) return } setSuccess("Match recorded successfully!") setIsLoading(false) // Reset form setFormData({ team1P1Id: null, team1P2Id: null, team2P1Id: null, team2P2Id: null, team1Score: 0, team2Score: 0, round: formData.round, table: formData.table, isCasual: false, }) // Refresh the page to show updated matches setTimeout(() => { router.refresh() }, 1000) } catch { setError("An error occurred. Please try again.") setIsLoading(false) } } return (
{error && (
{error}
)} {success && (
{success}
)} {/* Round and Table Selection */}
{/* Team 1 */}

Team 1 (Odds)

{hasPrefilledPlayers ? (

{players.find(p => p.id === prefilledP1)?.name || "Unknown Player"}

) : ( )}
{hasPrefilledPlayers ? (

{players.find(p => p.id === prefilledP2)?.name || "Unknown Player"}

) : ( )}
{/* Team 2 */}

Team 2 (Evens)

{hasPrefilledPlayers ? (

{players.find(p => p.id === prefilledP3)?.name || "Unknown Player"}

) : ( )}
{hasPrefilledPlayers ? (

{players.find(p => p.id === prefilledP4)?.name || "Unknown Player"}

) : ( )}
) }