import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import clsx from 'clsx';
import { useEffect, useState } from 'react';
import { useUserSession } from '@vertesia/ui/session';
import { ChevronsUpDown, X } from 'lucide-react';
import { Button, Styles, useFlag } from '@vertesia/ui/core';
import { SelectDocumentModal } from './SelectDocumentModal';
const STORE_REGEX = /store:([a-f0-9]+)/;
export function DocumentInput({ object }) {
    const { client } = useUserSession();
    const { off, on, isOn } = useFlag();
    const [actualValue, setValue] = useState(object.value != null ? String(object.value) : '');
    const [doc, setDoc] = useState(undefined);
    const _onChange = (event) => {
        const value = event.target.value;
        setValue(value);
        object.value = value;
    };
    const clearValue = () => {
        setValue('');
        object.value = '';
        setDoc(undefined);
    };
    const onSelect = (value) => {
        if (value) {
            const uri = "store:" + value.id;
            setValue(uri);
            setDoc(value || undefined);
            object.value = uri;
        }
        off();
    };
    useEffect(() => {
        if (!actualValue || doc) {
            return;
        }
        const match = actualValue.match(STORE_REGEX);
        if (!match) {
            return;
        }
        client.objects.get(match[1]).then((doc) => {
            setDoc(doc);
        }).catch(() => {
            clearValue();
        });
    }, [actualValue]);
    return (_jsxs("div", { children: [_jsxs("div", { className: "relative", children: [_jsx("input", { value: actualValue, onChange: _onChange, className: clsx(Styles.INPUT, "pr-10 w-full") }), doc &&
                        _jsx("div", { className: "absolute inset-y-0 right-10 flex items-center justify-center ", children: _jsx(Button, { onClick: clearValue, variant: 'unstyled', className: 'hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600', children: _jsx(X, { className: "size-5" }) }) }), _jsx("div", { className: "absolute inset-y-0 right-0 flex items-center justify-center", children: _jsx(Button, { onClick: on, variant: 'unstyled', className: 'hover:bg-gray-100 dark:hover:bg-gray-600', children: _jsx(ChevronsUpDown, { className: "size-5" }) }) }), _jsx(SelectDocumentModal, { value: actualValue, isOpen: isOn, onClose: onSelect })] }), doc &&
                _jsx("div", { className: "p-1 semibold text-sm text-gray-600 dark:text-slate-300", children: doc.properties?.title || doc.name })] }));
}
//# sourceMappingURL=DocumentInput.js.map