'use client'; import { useState, useEffect } from 'react'; import { useSession } from 'next-auth/react'; type Club = { id: string; name: string; sportType: string; description?: string; }; export function ClubManagement() { const { data: session } = useSession(); const [clubs, setClubs] = useState([]); const [loading, setLoading] = useState(true); const [isCreating, setIsCreating] = useState(false); const [newClub, setNewClub] = useState({ name: '', sportType: 'Tennis', description: '' }); useEffect(() => { const fetchClubsLocally = async () => { try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/admin/clubs`, { headers: { Authorization: `Bearer ${session?.accessToken}` }, }); if (res.ok) { const data = await res.json(); setClubs(data); } } catch (error) { console.error('Failed to fetch clubs', error); } finally { setLoading(false); } }; if (session) fetchClubsLocally(); }, [session]); const fetchClubs = async () => { try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/admin/clubs`, { headers: { Authorization: `Bearer ${session?.accessToken}` }, }); if (res.ok) { const data = await res.json(); setClubs(data); } } catch (error) { console.error('Failed to fetch clubs', error); } finally { setLoading(false); } }; const handleCreate = async (e: React.FormEvent) => { e.preventDefault(); try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/admin/clubs`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${session?.accessToken}`, }, body: JSON.stringify({ name: newClub.name, sportType: newClub.sportType === 'Tennis' ? 0 : 1, // Mapping Enum or keep string if api accepts description: newClub.description, }), }); if (res.ok) { setNewClub({ name: '', sportType: 'Tennis', description: '' }); setIsCreating(false); fetchClubs(); } } catch (e) { console.error(e); } }; const handleDelete = async (id: string) => { if (!confirm('Are you sure you want to delete this club?')) return; try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/admin/clubs/${id}`, { method: 'DELETE', headers: { Authorization: `Bearer ${session?.accessToken}` }, }); if (res.ok) { fetchClubs(); } } catch (e) { console.error(e); } }; if (loading) return
Loading clubs...
; return (

All Clubs

{isCreating && (

New Club

setNewClub({ ...newClub, name: e.target.value })} />