import { Button, IconBox, Input, Text } from '@citric/core'
import { PlusCircle, TimesCircle, Trash } from '@citric/icons'
import { IconButton } from '@citric/ui'
import { Dictionary, interpolate, useTranslate } from '@stack-spot/portal-translate'
import { useMemo, useState } from 'react'
import { FieldComponent } from '../../form/types'

export const SimpleListField: FieldComponent<(string | number)[], { type: 'int' | 'text', pattern?: string }> = (
  { value, onChange, disabled, name, type, pattern },
) => {
  const t = useTranslate(dictionary)
  const [current, setCurrent] = useState('')
  const [error, setError] = useState('')
  pattern = `^${pattern}$`

  function addItem() {
    if (!pattern || current.match(pattern)) {
      onChange([...(value ?? []), type === 'int' ? parseInt(current) : current])
      setCurrent('')
    } else {
      setError(interpolate(t.invalidPattern, pattern))
    }
  }

  function removeItem(index: number) {
    onChange(value?.filter((_, i) => i !== index))
  }

  function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === 'Enter') {
      addItem()
      e.preventDefault()
    }
  }

  function handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
    setCurrent(e.target.value)
    if (error && pattern && e.target.value.match(pattern)) {
      setError('')
    }
  }

  const items = useMemo(() => value?.map((v, i) => (
    <li key={i}>
      <Text appearance="microtext1">{v}</Text>
      <IconButton aria-label={t.remove} onClick={() => removeItem(i)}><Trash /></IconButton>
    </li>
  )), [value])

  return (
    <div className="simple-list-field">
      <div className="input-group">
        <Input
          name={name}
          disabled={disabled}
          type={type === 'text' ? 'text' : 'number'}
          value={current}
          onChange={handleInputChange}
          onKeyDown={onKeyDown}
        />
        <Button disabled={disabled || !current} onClick={addItem} colorScheme="inverse">
          <Text>{t.add}</Text>
          <IconBox><PlusCircle /></IconBox>
        </Button>
      </div>
      {error && <div className="error-message">
        <IconBox className="icon"><TimesCircle /></IconBox>
        <Text>{error}</Text>
      </div>}
      <ul className="current-value">{items}</ul>
    </div>
  )
}

const dictionary = {
  en: {
    add: 'Add',
    remove: 'Remove',
    invalidPattern: "The value doesn't match the expected pattern: $0.",
  },
  pt: {
    add: 'Adicionar',
    remove: 'Remover',
    invalidPattern: 'O valor não segue o padrão esperado: $0.',
  },
} satisfies Dictionary
