'use client'; import { useState, FormEvent } from 'react'; import { useRouter } from 'next/navigation'; import Input from '../ui/Input'; import Button from '../ui/Button'; import { League } from '@core/racing/domain/entities/League'; interface FormErrors { name?: string; description?: string; pointsSystem?: string; sessionDuration?: string; submit?: string; } export default function CreateLeagueForm() { const router = useRouter(); const [loading, setLoading] = useState(false); const [errors, setErrors] = useState({}); const [formData, setFormData] = useState({ name: '', description: '', pointsSystem: 'f1-2024' as 'f1-2024' | 'indycar', sessionDuration: 60 }); const validateForm = (): boolean => { const newErrors: FormErrors = {}; if (!formData.name.trim()) { newErrors.name = 'Name is required'; } else if (formData.name.length > 100) { newErrors.name = 'Name must be 100 characters or less'; } if (!formData.description.trim()) { newErrors.description = 'Description is required'; } else if (formData.description.length > 500) { newErrors.description = 'Description must be 500 characters or less'; } if (formData.sessionDuration < 1 || formData.sessionDuration > 240) { newErrors.sessionDuration = 'Session duration must be between 1 and 240 minutes'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); if (loading) return; if (!validateForm()) return; setLoading(true); try { const driverRepo = getDriverRepository(); const drivers = await driverRepo.findAll(); const currentDriver = drivers[0]; if (!currentDriver) { setErrors({ submit: 'No driver profile found. Please create a profile first.' }); setLoading(false); return; } const leagueRepo = getLeagueRepository(); const league = League.create({ id: crypto.randomUUID(), name: formData.name.trim(), description: formData.description.trim(), ownerId: currentDriver.id, settings: { pointsSystem: formData.pointsSystem, sessionDuration: formData.sessionDuration, qualifyingFormat: 'open', }, }); await leagueRepo.create(league); router.push(`/leagues/${league.id}`); router.refresh(); } catch (error) { setErrors({ submit: error instanceof Error ? error.message : 'Failed to create league' }); setLoading(false); } }; return ( <>
setFormData({ ...formData, name: e.target.value })} error={!!errors.name} errorMessage={errors.name} placeholder="European GT Championship" maxLength={100} disabled={loading} />

{formData.name.length}/100