import React from 'react'
import {
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownToggle,
  DropdownHeader,
} from './dropdown/dropdown-menu'
import { useTranslation } from 'react-i18next'
import getMeta from '@/utils/meta'
import MaterialIcon from '@/shared/components/material-icon'

function LanguagePicker({ showHeader } = { showHeader: false }) {
  const { t } = useTranslation()

  const currentLangCode = getMeta('ol-i18n').currentLangCode
  const footerMeta = getMeta('ol-footer')
  const translatedLanguages = footerMeta?.translatedLanguages
  const availableLanguages: string[] = footerMeta?.availableLanguages ?? []
  const currentUrl = window.location.pathname

  return (
    <Dropdown drop="up">
      <DropdownToggle
        id="language-picker-toggle"
        aria-label={t('select_a_language')}
        className="btn-inline-link"
        variant="link"
      >
        <MaterialIcon type="translate" />
        &nbsp;
        <span className="language-picker-text">
          {translatedLanguages?.[currentLangCode] ?? currentLangCode}
        </span>
      </DropdownToggle>

      <DropdownMenu
        className="dropdown-menu-sm-width"
        aria-labelledby="language-picker-toggle"
      >
        {showHeader ? <DropdownHeader>{t('language')}</DropdownHeader> : null}
        {availableLanguages
          .filter(lng => translatedLanguages?.[lng])
          .map(lng => {
            const isActive = lng === currentLangCode
            return (
              <li role="none" key={lng} translate="no">
                <DropdownItem
                  href={`/set-language?lng=${encodeURIComponent(lng)}&return_to=${encodeURIComponent(currentUrl)}`}
                  active={isActive}
                  aria-current={isActive ? 'true' : false}
                  trailingIcon={isActive ? 'check' : null}
                >
                  {translatedLanguages![lng]}
                </DropdownItem>
              </li>
            )
          })}
      </DropdownMenu>
    </Dropdown>
  )
}

export default LanguagePicker
