import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button } from "@powerhousedao/design-system";
import { format } from "date-fns";
import { useCallback, useId, useRef, useState } from "react";
import { Checkbox } from "../../ui/components/data-entry/checkbox/checkbox.js";
import { Form } from "../components/index.js";
function _isValidRegex(pattern) {
    try {
        new RegExp(pattern);
        return true;
    }
    catch {
        return false;
    }
}
export const withForm = (Story, context) => {
    const formRef = useRef(null);
    const [showFormButtons, setShowFormButtons] = useState(false);
    const [resetKey, setResetKey] = useState(0);
    const checkboxId = useId();
    const { viewMode, parameters } = context;
    const isDocs = viewMode === "docs";
    // Ensure we're properly accessing the parameters
    const formParameters = parameters.form;
    const resetBehavior = formParameters?.resetBehavior ?? "reset";
    const onReset = useCallback(() => {
        if (resetBehavior === "unmount") {
            setResetKey((prev) => prev + 1);
        }
        else {
            const defaultValues = Object.fromEntries(Object.keys(formRef.current?.control._fields ?? {}).map((fieldName) => [
                fieldName,
                formParameters?.defaultValues?.[fieldName] ?? "",
            ]));
            formRef.current?.reset(defaultValues);
        }
    }, [formParameters, resetBehavior]);
    const onSubmit = useCallback((data) => {
        // Allow to show bigInt values in the alert
        const serializedData = JSON.stringify(data, (key, value) => typeof value === "bigint" ? `BigInt(${value.toString()})` : value, 2);
        // delay the alert to allow component JS to finish the execution
        setTimeout(() => {
            alert(serializedData);
        }, 300);
    }, []);
    const onShowFormButtonsChange = useCallback((checked) => {
        setShowFormButtons(checked);
    }, []);
    // override the warnings in the args to avoid breaking the storybook
    // as storybook set by default an object instead of an array
    const overrideArgs = {
        ...context.args,
        ...(Array.isArray(context.args.warnings)
            ? { warnings: context.args.warnings }
            : { warnings: undefined }),
        ...(context.args.pattern !== undefined
            ? _isValidRegex(context.args.pattern)
                ? { pattern: context.args.pattern }
                : { pattern: "" }
            : {}),
    };
    return (_jsxs("div", { children: [_jsxs(Form, { ref: formRef, onSubmit: onSubmit, children: [_jsx(Story, { args: overrideArgs }), showFormButtons || isDocs ? (_jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { className: "mt-4 w-full", color: "light", type: "reset", onClick: onReset, children: "Reset" }), _jsx(Button, { className: "mt-4 w-full", color: "dark", type: "submit", children: "Submit" })] })) : (
                    // allow to "submit" the form from the story
                    // it is needed as some browsers do not submit on Enter key press when there're several inputs and no submit button
                    _jsx("input", { type: "submit", className: "hidden" }))] }, resetKey), !isDocs && (_jsx("div", { className: "absolute bottom-5 right-5 z-50", children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Checkbox, { id: checkboxId, value: showFormButtons, onChange: onShowFormButtonsChange }), _jsx("label", { className: "cursor-pointer dark:text-gray-400", htmlFor: checkboxId, children: "Show form buttons" })] }) }))] }));
};
export const withTimestampsAsISOStrings = (Story, context) => {
    const { args } = context;
    // Function to convert timestamps to Date objects
    const convertTimestampsToDates = (args) => {
        const newArgs = { ...args };
        // Iterate through all args properties
        Object.keys(newArgs).forEach((key) => {
            const value = newArgs[key];
            if ((key === "minDate" || key === "maxDate") &&
                typeof value === "string") {
                const timestamp = new Date(value).getTime();
                if (!isNaN(timestamp)) {
                    const date = new Date(timestamp);
                    date.setHours(12, 0, 0, 0);
                    // Format that Storybook accepts: "22-Mar-2025"
                    newArgs[key] = format(date, "dd-MMM-yyyy");
                }
            }
            if (typeof value === "number" && value > 1609459200000) {
                const date = new Date(value);
                date.setHours(12, 0, 0, 0);
                newArgs[key] = format(date, "dd-MMM-yyyy");
            }
        });
        return newArgs;
    };
    const convertedArgs = convertTimestampsToDates(args);
    return _jsx(Story, { ...context, args: convertedArgs });
};
//# sourceMappingURL=decorators.js.map