import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button, IconBox, Input, Text } from '@citric/core';
import { PlusCircle, TimesCircle, Trash } from '@citric/icons';
import { IconButton } from '@citric/ui';
import { interpolate, useTranslate } from '@stack-spot/portal-translate';
import { useMemo, useState } from 'react';
export const SimpleListField = ({ 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) {
        onChange(value?.filter((_, i) => i !== index));
    }
    function onKeyDown(e) {
        if (e.key === 'Enter') {
            addItem();
            e.preventDefault();
        }
    }
    function handleInputChange(e) {
        setCurrent(e.target.value);
        if (error && pattern && e.target.value.match(pattern)) {
            setError('');
        }
    }
    const items = useMemo(() => value?.map((v, i) => (_jsxs("li", { children: [_jsx(Text, { appearance: "microtext1", children: v }), _jsx(IconButton, { "aria-label": t.remove, onClick: () => removeItem(i), children: _jsx(Trash, {}) })] }, i))), [value]);
    return (_jsxs("div", { className: "simple-list-field", children: [_jsxs("div", { className: "input-group", children: [_jsx(Input, { name: name, disabled: disabled, type: type === 'text' ? 'text' : 'number', value: current, onChange: handleInputChange, onKeyDown: onKeyDown }), _jsxs(Button, { disabled: disabled || !current, onClick: addItem, colorScheme: "inverse", children: [_jsx(Text, { children: t.add }), _jsx(IconBox, { children: _jsx(PlusCircle, {}) })] })] }), error && _jsxs("div", { className: "error-message", children: [_jsx(IconBox, { className: "icon", children: _jsx(TimesCircle, {}) }), _jsx(Text, { children: error })] }), _jsx("ul", { className: "current-value", children: items })] }));
};
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.',
    },
};
//# sourceMappingURL=SimpleListField.js.map