import map from 'lodash/map'

import { langsList } from 'config/languages'

import { OutsideClick } from 'features/OutsideClick'

import { useLanguageSelect } from './hooks'
import {
  Wrapper,
  Button,
  ButtonTitle,
  ListWrapper,
  LangsList,
  LangsItem,
  FlagIcon,
  LangName,
} from './styled'

export const LanguageSelect = () => {
  const {
    close,
    handleLangChange,
    isOpen,
    open,
    selectedLang,
  } = useLanguageSelect()

  return (
    <Wrapper>
      {selectedLang && (
        <Button
          type='button'
          aria-controls='langsList'
          aria-expanded={isOpen}
          onClick={open}
        >
          <FlagIcon flag={selectedLang.className} />
          <ButtonTitle>{selectedLang.title}</ButtonTitle>
        </Button>
      )}
      {isOpen && (
        <OutsideClick onClick={close}>
          <ListWrapper>
            <LangsList id='langsList'>
              {
                map(
                  langsList,
                  ({
                    className,
                    locale,
                    title,
                  }) => (
                    <LangsItem
                      key={locale}
                      selected={selectedLang?.locale === locale}
                      onClick={handleLangChange(locale)}
                    >
                      <FlagIcon flag={className} />
                      <LangName>{title}</LangName>
                    </LangsItem>
                  ),
                )
              }
            </LangsList>
          </ListWrapper>
        </OutsideClick>
      )}
    </Wrapper>
  )
}
