import { useState, useEffect, useCallback, useRef } from 'react'
import type { AxiosInstance } from 'axios'

export function useApi<T>(
  client: AxiosInstance,
  url: string,
  opts: { immediate?: boolean; deps?: unknown[] } = {}
) {
  const { immediate = true, deps = [] } = opts
  const [data, setData]       = useState<T | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError]     = useState<string | null>(null)
  const mounted = useRef(true)

  useEffect(() => { mounted.current = true; return () => { mounted.current = false } }, [])

  const fetch = useCallback(async () => {
    setLoading(true); setError(null)
    try {
      const res = await client.get<T>(url)
      if (mounted.current) setData(res.data)
    } catch (e: unknown) {
      if (mounted.current) {
        const msg = (e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '오류가 발생했습니다.'
        setError(msg)
      }
    } finally {
      if (mounted.current) setLoading(false)
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url, ...deps])

  useEffect(() => { if (immediate) fetch() }, [fetch, immediate])

  return { data, loading, error, refetch: fetch }
}
