import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from 'react';
import { css } from '@emotion/react';
import { Type } from '@sinclair/typebox';
import { createComponent } from '@meta-ui/core';
import { Button, VStack } from '@chakra-ui/react';
import { watch } from '../../../utils/watchReactivity';
import Slot from '../../_internal/Slot';
const FormImpl = ({ mergeState, subscribeMethods, hideSubmit, slotsMap, callbackMap, services, }) => {
    const [invalidArray, setInvalidArray] = useState([]);
    const [isFormInvalid, setIsFormInvalid] = useState(false);
    const formDataRef = useRef({});
    const formControlIds = useMemo(() => {
        var _a;
        return (((_a = slotsMap === null || slotsMap === void 0 ? void 0 : slotsMap.get('content')) === null || _a === void 0 ? void 0 : _a.map(slot => {
            return slot.id;
        })) || []);
    }, [slotsMap]);
    useEffect(() => {
        setInvalidArray(formControlIds.map(fcid => {
            return services.stateManager.store[fcid].isInvalid;
        }));
    }, []);
    useEffect(() => {
        const disable = invalidArray.some(v => v);
        setIsFormInvalid(disable);
        mergeState({
            disableSubmit: disable,
        });
    }, [invalidArray]);
    useEffect(() => {
        subscribeMethods({
            resetForm() {
                formControlIds.forEach(fcId => {
                    const inputId = services.stateManager.store[fcId].inputId;
                    services.apiService.send('uiMethod', {
                        componentId: inputId,
                        name: 'resetInputValue',
                    });
                });
            },
        });
    }, [formControlIds]);
    useEffect(() => {
        const stops = [];
        formControlIds.forEach((fcId, i) => {
            let stop = watch(() => {
                return services.stateManager.store[fcId].isInvalid;
            }, newV => {
                setInvalidArray(oldValidArray => {
                    const newValidArray = [...oldValidArray];
                    newValidArray[i] = newV;
                    return newValidArray;
                });
            });
            stops.push(stop);
            stop = watch(() => {
                return services.stateManager.store[fcId].value;
            }, newV => {
                const fcState = services.stateManager.store[fcId];
                formDataRef.current[fcState.fieldName] = newV;
                mergeState({ data: Object.assign({}, formDataRef.current) });
            });
            stops.push(stop);
        });
        return () => {
            stops.forEach(s => {
                s();
            });
        };
    }, [formControlIds]);
    const onSubmit = () => {
        callbackMap === null || callbackMap === void 0 ? void 0 : callbackMap.onSubmit();
    };
    const style = css `
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    padding: var(--chakra-space-4);
    background: white;
    border: 1px solid var(--chakra-colors-gray-200);
    border-radius: 4px;
  `;
    return (_jsxs(VStack, Object.assign({ css: style, spacing: "5" }, { children: [_jsx(Slot, { slotsMap: slotsMap, slot: "content" }, void 0), hideSubmit ? undefined : (_jsx(Button, Object.assign({ marginInlineStart: "auto !important", disabled: isFormInvalid, onClick: onSubmit }, { children: "\u63D0\u4EA4" }), void 0))] }), void 0));
};
const PropsSchema = Type.Object({
    hideSubmit: Type.Boolean(),
});
export default Object.assign(Object.assign({}, createComponent({
    version: 'chakra_ui/v1',
    metadata: {
        name: 'form',
        displayName: 'Form',
        description: 'chakra-ui form',
        isDraggable: true,
        isResizable: true,
        exampleProperties: {
            hideSubmit: false,
        },
        exampleSize: [4, 6],
    },
    spec: {
        properties: PropsSchema,
        state: Type.Object({
            data: Type.Any(),
            disableSubmit: Type.Boolean(),
        }),
        methods: [
            {
                name: 'resetForm',
            },
        ],
        slots: ['content'],
        styleSlots: [],
        events: ['onSubmit'],
    },
})), { impl: FormImpl });
//# sourceMappingURL=Form.js.map