import React from 'react'

import map from 'lodash/map'

import { useLexicsStore } from 'features/LexicsStore'
import { OutsideClick } from 'features/OutsideClick'

import { useToggle } from 'hooks'

import { langsList } from './config'
import {
  Wrapper,
  WorldIcon,
  LangsList,
  LangsItem,
  FlagIcon,
} from './styled'
import './flags.scss'

export const LanguageSelect = () => {
  const { changeLang, translate } = useLexicsStore()
  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const handleLangChange = (locale: string) => () => {
    changeLang(locale)
    close()
  }

  return (
    <OutsideClick onClick={close}>
      <Wrapper>
        <WorldIcon
          onClick={open}
          active={isOpen}
          title={translate('select_language')}
          aria-expanded={isOpen}
          aria-controls='langsList'
        />
        {isOpen && (
          <LangsList id='langsList'>
            {
              map(
                langsList,
                ({
                  className,
                  locale,
                  title,
                }) => (
                  <LangsItem
                    key={locale}
                    title={title}
                    onClick={handleLangChange(locale)}
                  >
                    <FlagIcon
                      className={`
                        flag-icon
                        flag-icon-24x16
                        flag-icon-${className}
                      `}
                    />
                  </LangsItem>
                ),
              )
            }
          </LangsList>
        )}
      </Wrapper>
    </OutsideClick>
  )
}
