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

import { getManagerDependingVariables } from "@devowl-wp/cookie-consent-web-client";

import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { useUpsell } from "../../../../../contexts/upsell.js";
import { FormServiceLayout } from "../../../layout.js";
import { FormValueDifferFromTemplateTag } from "../../../valueDifferFromTemplateTag.js";

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

const FormServiceFieldHandlingExecuteCodeWhenNoTagManagerConsentIsGiven: FC<{ name: keyof FormServiceValueProps }> = ({
    name,
}) => {
    const { __, _i } = useI18n();
    const { isPro } = useUpsell();
    const { setCookiesViaManager, isGcm, template } = useFormService();
    const [ref, setRef] = useState<HTMLDivElement>();

    const { managerLabel, features } = getManagerDependingVariables(setCookiesViaManager, {
        isGcm,
        presetId: template?.identifier,
    });
    const executeCodeWhenNoTagManagerConsentIsGivenLabel = _i(
        __("Only run this script if the user has {{u}}not{{/u}} allowed to use %s", managerLabel),
        {
            u: <u />,
        },
    );

    return isPro && features.executeCodeWhenNoTagManagerConsentIsGiven ? (
        <Form.Item<FormServiceValueProps>
            required
            wrapperCol={{
                offset: FormServiceLayout.labelCol.span,
                span: FormServiceLayout.wrapperCol.span,
            }}
        >
            <Form.Item<FormServiceValueProps> name={name} valuePropName="checked" noStyle>
                <Switch />
            </Form.Item>
            <span>
                &nbsp;&nbsp;
                {executeCodeWhenNoTagManagerConsentIsGivenLabel}
            </span>
            <div style={{ marginTop: 10 }} ref={setRef}>
                <FormValueDifferFromTemplateTag
                    form="service"
                    valueName={name}
                    widthOfRef={ref}
                    renderDiff={(value: boolean) => (
                        <>
                            <Switch disabled checked={value} />
                            <span>
                                &nbsp;&nbsp;
                                {executeCodeWhenNoTagManagerConsentIsGivenLabel}
                            </span>
                        </>
                    )}
                    noBr
                />
            </div>
        </Form.Item>
    ) : null;
};

export { FormServiceFieldHandlingExecuteCodeWhenNoTagManagerConsentIsGiven };
