/* eslint-disable react/display-name */
import { IconBox, Input, Text } from '@citric/core'
import { Code, Filter } from '@citric/icons'
import { FieldAddon, FieldGroup } from '@citric/ui'
import { Dictionary, useTranslate } from '@stack-spot/portal-translate'
import { forwardRef, useMemo, useState } from 'react'
import { useContextVariables } from '../VariablesContext'

interface Props {
  pattern?: string,
  onSelect: (expression: string) => void,
}

export const VariableSelector = forwardRef<HTMLDivElement, Props>(({ pattern, onSelect }, ref) => {
  const t = useTranslate(dictionary)
  const variables = useContextVariables()
  const [search, setSearch] = useState('')
  const [accountItems, stackspotItems] = useMemo(() => {
    const accountItems: React.ReactElement[] = []
    const stackspotItems: React.ReactElement[] = []
    for (const name in variables) {
      const variable = variables[name]
      if (
        (!pattern || `${variable.get()}`.match(`^${pattern}$`)) &&
        (variable.path.includes(search) || variable.metadata?.description?.includes(search))
      ) {
        const items = ['account', 'workspace'].includes(variable.metadata?.source ?? '') ? accountItems : stackspotItems
        items.push(
          <li key={variable.path}>
            <button onClick={() => onSelect(`{{ ${variable.path} }}`)}>
              <IconBox size="xs"><Code /></IconBox>
              <div className="variable-data">
                <Text>{variable.path}</Text>
                <Text appearance="microtext1" colorScheme="light.700">{`${variable.get()}`}</Text>
              </div>
            </button>
          </li>,
        )
      }
    }
    return [accountItems, stackspotItems]
  }, [pattern, search, variables])

  return (
    <div ref={ref} className="variable-selector">
      <FieldGroup className="search">
        <FieldAddon>
          <IconBox size="sm" colorIcon="light.700">
            <Filter />
          </IconBox>
        </FieldAddon>
        <Input
          value={search}
          placeholder={t.filter}
          onChange={(e) => setSearch(e.target.value)}
          maxLength={255}
        />
      </FieldGroup>
      {!!accountItems?.length && <section>
        <Text appearance="h5">{t.account}</Text>
        <ul>{accountItems}</ul>
      </section>}
      {!!stackspotItems?.length && <section>
        <Text appearance="h5">{t.stackspot}</Text>
        <ul>{stackspotItems}</ul>
      </section>}
      {!accountItems.length && !stackspotItems.length && <Text colorScheme="light.700" align="center" mb="16px">{t.noVariables}</Text>}
    </div>
  )
})

const dictionary = {
  en: {
    account: 'Account variables',
    stackspot: 'StackSpot variables',
    filter: 'Filter variables',
    noVariables: 'There are no variables available.',
  },
  pt: {
    account: 'Variáveis da conta',
    stackspot: 'Variáveis StackSpot',
    filter: 'Filtrar variáveis',
    noVariables: 'Não há variáveis disponíveis.',
  },
} satisfies Dictionary
