import { css } from "@emotion/css"
import { memo, useState } from "react"
import { useTranslation } from "react-i18next"
import Icon from "@aet/icons/macro"
import { useUpdateEffect } from "@react-hookz/web"
import styled from "@emotion/styled"
import { useEvent } from "@aet/hooks"
import { getLocale, setLanguage } from "~/shared/i18n"
import { FormEntry, Input } from "./styled"

const AUTO = "autoDetect"

const endonyms = Object.entries({
  "en-US": "English",
  "fr-CA": "Français (Canada)",
  "es-ES": "Español",
  "de-DE": "Deutsch",
  "ja-JP": "日本語",
  "zh-CN": "简体中文",
  "zh-TW": "繁體中文",
})

export const LocalePicker = memo(() => {
  const { t, i18n } = useTranslation()
  const [lang, setLang] = useState<string | null>(() => getLocale() ?? AUTO)

  useUpdateEffect(() => {
    if (lang === AUTO) {
      setLanguage(null)
      i18n.changeLanguage(getLocale())
    } else {
      setLanguage(lang)
      i18n.changeLanguage(lang!)
    }
  }, [lang])

  return (
    <FormEntry>
      <label
        className={css`
          display: flex;
          align-items: center;
          > svg {
            margin-bottom: -1px;
            margin-right: 2px;
          }
        `}
      >
        <Icon icon="IoLanguage" />
        <span>{t("preferences.language")}</span>
      </label>
      <Select
        as="select"
        value={lang ?? AUTO}
        className={css`
          padding: 6px 12px;
        `}
        onChange={useEvent(e => {
          const { value } = e.target
          setLang(value)
        })}
      >
        <option value={AUTO}>{t("preferences.autoDetect")}</option>
        {endonyms.map(([locale, endonym]) => (
          <option key={locale} value={locale}>
            {endonym}
          </option>
        ))}
      </Select>
    </FormEntry>
  )
})

export const Select = styled(Input)`
  && {
    padding: 6px 7px;
  }
`
