import { useEffect, useState } from 'react'
import { fetchMatches, type MatchResponse } from './matchApi'

export function useMatches(token: string, competitionId: number | null) {
  const [matches, setMatches] = useState<MatchResponse[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (competitionId === null) {
      setMatches([])
      return
    }

    let isActive = true
    setLoading(true)
    setError(null)

    async function load() {
      try {
        const data = await fetchMatches(token, competitionId!)
        if (isActive) {
          setMatches(data)
        }
      } catch (err) {
        if (isActive) {
          setError(err instanceof Error ? err.message : 'Failed to load matches')
        }
      } finally {
        if (isActive) {
          setLoading(false)
        }
      }
    }

    void load()

    return () => {
      isActive = false
    }
  }, [token, competitionId])

  return { matches, loading, error }
}
