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'
import { useLexicsStore } from 'features/LexicsStore'

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

type Names = 'name_eng' | 'name_rus'

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

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

  return countries
}

export const useCountries = () => {
  const countries = useCountriesList()
  const { suffix } = useLexicsStore()
  const [selectedCountry, setSelectedCountry] = useState<SelectedCountry>(null)

  const nameField = `name_${suffix}` as Names

  const transformedCountries = useMemo(
    () => orderBy(
      map(countries, (country) => ({
        ...country,
        name: country[nameField],
      })),
      'name',
    ),
    [countries, nameField],
  )

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