import * as React from 'react'
import getFormValues from '@theoryofnekomata/formxtra/dist/index';
import getNumberName from '../../core/src';
import enGB from '../../core/src/locales/variants/en-GB';
import enPH from '../../core/src/locales/variants/en-PH';
import deDE from '../../core/src/locales/variants/de-DE';

const App = () => {
  const [numberName, setNumberName] = React.useState('')

  const computeNumberName = (form: HTMLFormElement) => {
    const { number: x, locale: localeStr } = getFormValues(form) as { number: string, locale: string }
    const { [localeStr]: locale = enPH } = {
      'en-PH': enPH,
      'en-GB': enGB,
      'de-DE': deDE,
    } as Record<string, (...args: unknown[]) => string>
    let numberName: string
    try {
      numberName = getNumberName(
        x
          .replaceAll(' ', '')
          .replaceAll('_', '')
          .replaceAll(',', ''),
        {
          locale,
        }
      )
    } catch {
      numberName = ''
    }
    setNumberName(numberName)
  }

  const handleSubmit: React.FormEventHandler = e => {
    computeNumberName(e.target as HTMLFormElement)
  }

  const handleChange: React.ChangeEventHandler<HTMLTextAreaElement | HTMLSelectElement> = e => {
    computeNumberName(e.target.form as HTMLFormElement)
  }

  return (
    <form
      onSubmit={handleSubmit}
    >
      <select
        name="locale"
        className="locale"
        aria-label="Locale"
        onChange={handleChange}
      >
        <optgroup
          label="English (English)"
        >
          <option
            value="en-PH"
          >
            Philippines
          </option>
          <option
            value="en-GB"
          >
            United Kingdom
          </option>
        </optgroup>
        <optgroup
          label="Deutsch (German)"
        >
          <option
            value="de-DE"
          >
            Germany
          </option>
        </optgroup>
      </select>
      <textarea
        name="number"
        onChange={handleChange}
        placeholder="Enter a number, e.g. 1000, 1e+45"
        className="input"
        aria-label="Input"
      />
      <textarea
        placeholder="Its name goes here"
        readOnly
        value={numberName}
        className="output"
        aria-label="Output"
      />
    </form>
  )
}

export default App
