import { Form } from "antd";
import { useCallback, useState } from "react";

import { FormServiceFieldHandlingExecuteCodeWhenNoTagManagerConsentIsGiven } from "./executeCodeWhenNoTagManagerConsentIsGiven.js";
import { FormServiceFieldHandlingSkipIfActiveNotice } from "./skipIfActiveNotice.js";
import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { FormValueDifferFromTemplateTag } from "../../../valueDifferFromTemplateTag.js";

import type { FormServiceValueProps } from "../../../../../types/formService.js";
import type { FC } from "react";

const FormServiceFieldHandlingCodeOptOut: FC = () => {
    const { __ } = useI18n();
    const { renderCodeMirror, essentialGroupId } = useFormService();
    const [ref, setRef] = useState<HTMLDivElement>();

    // CodeMirror does not support "display:none;", we need to hide it in a hacky way
    const createHiddenFormItemsWithCodeMirror = useCallback(
        (visible: boolean) => ({
            opacity: visible ? undefined : 0,
            height: visible ? undefined : 0,
            margin: visible ? undefined : 0,
        }),
        [],
    );

    return (
        <Form.Item<FormServiceValueProps>
            noStyle
            shouldUpdate={(prevValues, nextValues) => prevValues.group !== nextValues.group}
        >
            {({ getFieldValue }) => {
                const visible = getFieldValue("group") !== essentialGroupId;

                return (
                    <>
                        <Form.Item<FormServiceValueProps>
                            label={__("Code executed on opt-out")}
                            style={createHiddenFormItemsWithCodeMirror(visible)}
                        >
                            <Form.Item name="codeOptOut" noStyle>
                                {renderCodeMirror()}
                            </Form.Item>
                            <FormServiceFieldHandlingSkipIfActiveNotice name="codeOptOut" />
                            <div ref={setRef}>
                                <FormValueDifferFromTemplateTag
                                    style={{ marginTop: 10 }}
                                    form="service"
                                    valueName="codeOptOut"
                                    widthOfRef={ref}
                                    noBr
                                    splitView={false}
                                />
                            </div>
                        </Form.Item>
                        {visible && (
                            <>
                                <FormServiceFieldHandlingExecuteCodeWhenNoTagManagerConsentIsGiven name="executeCodeOptOutWhenNoTagManagerConsentIsGiven" />
                            </>
                        )}
                    </>
                );
            }}
        </Form.Item>
    );
};

export { FormServiceFieldHandlingCodeOptOut };
