import { useEffect, useRef, useState } from 'react'
import { fetchGroups, type GroupDto } from './groupApi'

export function useGroups(token: string, competitionId: number | null) {
  const [groups, setGroups] = useState<GroupDto[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const abortRef = useRef<AbortController | null>(null)

  const load = () => {
    if (!competitionId) {
      setGroups([])
      return
    }
    abortRef.current?.abort()
    abortRef.current = new AbortController()
    setLoading(true)
    setError(null)
    fetchGroups(token, competitionId)
      .then((data) => {
        setGroups(data)
        setLoading(false)
      })
      .catch((err: unknown) => {
        if (err instanceof Error && err.name === 'AbortError') return
        setError(err instanceof Error ? err.message : 'Failed to load groups')
        setLoading(false)
      })
  }

  useEffect(() => {
    load()
    return () => abortRef.current?.abort()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, competitionId])

  return { groups, loading, error, refetch: load }
}
