import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { useEffect, useMemo, useState } from 'react';
import { first } from 'lodash-es';
import { createComponent } from '@meta-ui/core';
import { Type } from '@sinclair/typebox';
import { FormControl, FormErrorMessage, FormHelperText, FormLabel, Text, } from '@chakra-ui/react';
import { watch } from '../../../utils/watchReactivity';
import { FormControlContentCSS, FormControlCSS, FormItemCSS, FormLabelCSS, } from './FormCSS';
import Slot from '../../_internal/Slot';
const FormControlImpl = ({ label, fieldName, isRequired, helperText, slotsMap, mergeState, services }) => {
    const [inputValue, setInputValue] = useState('');
    const [hideInvalid, setHideInvalid] = useState(true);
    const inputId = useMemo(() => { var _a; return ((_a = first(slotsMap === null || slotsMap === void 0 ? void 0 : slotsMap.get('content'))) === null || _a === void 0 ? void 0 : _a.id) || ''; }, []);
    const [validResult, setValidResult] = useState({
        isInvalid: false,
        errorMsg: '',
    });
    const { isInvalid, errorMsg } = validResult;
    useEffect(() => {
        if (!inputId)
            return;
        const stop = watch(() => {
            const inputState = services.stateManager.store[inputId];
            if (!inputState)
                return '';
            if (inputState.checked !== undefined) {
                return inputState.checked;
            }
            else {
                return inputState.value;
            }
        }, newV => {
            setInputValue(newV);
        });
        setInputValue(services.stateManager.store[inputId].value);
        return stop;
    }, [inputId, setInputValue]);
    useEffect(() => {
        var _a;
        if (!inputId)
            return;
        const stop = watch(() => {
            var _a;
            return (_a = services.stateManager.store[inputId]) === null || _a === void 0 ? void 0 : _a.validResult;
        }, newV => {
            setValidResult(newV);
        });
        if ((_a = services.stateManager.store[inputId]) === null || _a === void 0 ? void 0 : _a.validResult) {
            setValidResult(services.stateManager.store[inputId].validResult);
        }
        return stop;
    }, [inputId, setValidResult]);
    useEffect(() => {
        if (!inputId)
            return;
        if (inputValue) {
            setHideInvalid(false);
        }
        mergeState({
            inputId: inputId,
            fieldName,
            isInvalid: !!(isInvalid || (!inputValue && isRequired)),
            value: inputValue,
        });
    }, [inputId, inputId, fieldName, isInvalid, isRequired, inputValue]);
    const placeholder = _jsx(Text, Object.assign({ color: "gray.200" }, { children: "Please Add Input Here" }), void 0);
    const slotView = _jsx(Slot, { css: FormItemCSS, slotsMap: slotsMap, slot: "content" }, void 0);
    return (_jsxs(FormControl, Object.assign({ isRequired: isRequired, isInvalid: !hideInvalid && (isInvalid || (!inputValue && isRequired)), css: FormControlCSS }, { children: [_jsxs("div", Object.assign({ css: FormControlContentCSS }, { children: [_jsx(FormLabel, Object.assign({ css: FormLabelCSS }, { children: label }), void 0), inputId ? slotView : placeholder] }), void 0), errorMsg ? (_jsx(FormErrorMessage, Object.assign({ css: FormItemCSS }, { children: errorMsg }), void 0)) : undefined, helperText ? (_jsx(FormHelperText, Object.assign({ css: FormItemCSS }, { children: helperText }), void 0)) : undefined] }), void 0));
};
const PropsSchema = Type.Object({
    label: Type.String(),
    fieldName: Type.String(),
    isRequired: Type.Boolean(),
    helperText: Type.String(),
});
export default Object.assign(Object.assign({}, createComponent({
    version: 'chakra_ui/v1',
    metadata: {
        name: 'formControl',
        isResizable: false,
        isDraggable: true,
        displayName: 'Form Control',
        description: 'chakra-ui formControl',
        exampleProperties: {
            label: 'name',
            fieldName: 'name',
            isRequired: false,
            helperText: '',
        },
        exampleSize: [4, 2],
    },
    spec: {
        properties: PropsSchema,
        state: Type.Object({
            inputId: Type.String(),
            fieldName: Type.String(),
            isInvalid: Type.Boolean(),
            value: Type.Any(),
        }),
        methods: [],
        slots: ['content'],
        styleSlots: [],
        events: [],
    },
})), { impl: FormControlImpl });
//# sourceMappingURL=FormControl.js.map