import { Button, IconBox, Input } from '@citric/core'
import { ChevronDown } from '@citric/icons'
import { listToClass } from '@stack-spot/portal-theme'
import { Dictionary, useTranslate } from '@stack-spot/portal-translate'
import { useEffect, useMemo, useRef, useState } from 'react'
import { FieldComponent } from '../../form/types'
import { VariableSelector } from './VariableSelector'

const variablePattern = /\{\{[^{}]+\}\}/

export const VariableField: FieldComponent<string, Record<string, never>> = ({ name, onChange, value, disabled, onBlur, variable }) => {
  const t = useTranslate(dictionary)
  const [isOpen, setOpen] = useState(false)
  const isVariable = useMemo(() => value && variablePattern.test(value), [value])
  const selector = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!isOpen) return
    function onClick(e: MouseEvent) {
      if (e.target && !selector.current?.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('click', onClick)
    return () => document.removeEventListener('click', onClick)
  }, [isOpen])

  return (
    <div className={listToClass(['variable-field', isOpen && 'open', isVariable && 'variable'])}>
      <Input
        type="text"
        value={value}
        onChange={e => onChange(e.target.value)}
        name={name}
        disabled={disabled}
        onBlur={onBlur}
      />
      {!disabled && <Button
        type="button"
        appearance="outlined"
        colorScheme="inverse"
        onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
          setOpen(v => !v)
          e.stopPropagation()
        }}>
        {t.useVariable}
        <IconBox className="chevron"><ChevronDown /></IconBox>
      </Button>}
      <VariableSelector ref={selector} pattern={variable.config.metadata?.pattern} onSelect={onChange} />
    </div>
  )
}

const dictionary = {
  en: {
    useVariable: 'Use variable',
  },
  pt: {
    useVariable: 'Usar variável',
  },
} satisfies Dictionary
