import {
  useEffect,
  useState,
  useMemo,
} from 'react'

import orderBy from 'lodash/orderBy'
import map from 'lodash/map'

import type { Countries, Country } from 'requests'
import { getCountries } from 'requests'

export type SelectedCountry = (Country & {
  name: string,
}) | null

const useCountriesList = () => {
  const [countries, setCountries] = useState<Countries>([])

  useEffect(() => {
    getCountries().then(setCountries)
  }, [])

  return countries
}

export const useCountries = () => {
  const countries = useCountriesList()
  const [selectedCountry, setSelectedCountry] = useState<SelectedCountry>(null)
  const transformedCountries = useMemo(
    () => orderBy(
      map(countries, (country) => ({
        ...country,
        name: country.name_eng,
      })),
      ({ name }) => name,
    ),
    [countries],
  )

  return {
    countries: transformedCountries,
    selectedCountry,
    setSelectedCountry,
  }
}
