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

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

import type { Countries, Country } from 'requests'
import { getCountries } from 'requests'
import { getUsaStates, UsaStateType } from 'requests/getUsaStates'

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

export type SelectedState = (UsaStateType & {
  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 [usaStates, setUsaStates] = useState<Array<UsaStateType>>([])
  const [selectedState, setSelectedState] = useState<SelectedState>(null)

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

  useEffect(() => {
    if (selectedCountry?.id === 194) {
      (async () => {
        const states = await getUsaStates()
        setUsaStates(states)
      })()
    }
  }, [selectedCountry])

  return {
    countries: transformedCountries,
    selectedCountry,
    selectedState,
    setSelectedCountry,
    setSelectedState,
    setUsaStates,
    usaStates: usaStates.map((state: UsaStateType) => ({ ...state, name: state.name_eng })),
  }
}
