import map from 'lodash/map'

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

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()
  const { languageList } = useLexicsStore()

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