import { pikku } from '@/pikku/http'
import { useQuery } from '@tanstack/react-query'
import { CountriesMap } from '@heygermany/sdk'
import { SUPPORTED_COUNTRIES, SUPPORTED_COUNTRY_NAMES } from '@heygermany/sdk/config'
import { useI18n } from '@/context/i18n-provider'
import { useMemo } from 'react'

export const useGetCountries = () => {
  const { locale } = useI18n()

  const query = useQuery({
    queryKey: ['countries', locale],
    queryFn: async (): Promise<CountriesMap> => {
      return await pikku().get('/countries', { locale })
    },
    staleTime: 60 * 60 * 1000, // 1 hour
  })

  const fallbackCountriesMap = useMemo(() => {
    return SUPPORTED_COUNTRIES.reduce((acc, code) => {
      acc[code] = SUPPORTED_COUNTRY_NAMES[code]
      return acc
    }, {} as CountriesMap)
  }, [])

  const countriesMap = useMemo(() => {
    if (query.data && Object.keys(query.data).length > 0) {
      return query.data
    }

    return fallbackCountriesMap
  }, [fallbackCountriesMap, query.data])

  const getCountryNameFromAbbreviation = useMemo(() => {
    return (abbreviation: string | null | undefined): string => {
      if (!abbreviation) return 'N/A'
      return countriesMap[abbreviation] || abbreviation
    }
  }, [countriesMap])

  return {
    ...query,
    data: countriesMap,
    getCountryNameFromAbbreviation
  }
}
