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

import { EServiceTemplateLegalBasis } from "@devowl-wp/api-real-cookie-banner";

import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { Notices } from "../../../../common/notices.js";
import { FormValueDifferFromTemplateTag } from "../../../valueDifferFromTemplateTag.js";

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

const Field: FC<ComponentProps<typeof Radio.Group> & { overwriteValue?: FormServiceValueProps["legalBasis"] }> = (
    props,
) => {
    const { __ } = useI18n();
    const { allowLegalBasisLegalRequirement } = useFormService();

    return (
        <Radio.Group {...props} value={props.overwriteValue || props.value}>
            <Radio.Button value={EServiceTemplateLegalBasis.Consent}>{__("Consent (Opt-in)")}</Radio.Button>
            <Radio.Button value={EServiceTemplateLegalBasis.LegitimateInterest}>
                {__("Legitimate interest (Opt-out)")}
            </Radio.Button>
            {allowLegalBasisLegalRequirement && (
                <Radio.Button value={EServiceTemplateLegalBasis.LegalRequirement}>
                    {__("Compliance with a legal obligation")}
                </Radio.Button>
            )}
        </Radio.Group>
    );
};

const FormServiceFieldGeneralLegalBasis: FC = () => {
    const { __, _i } = useI18n();
    const {
        allowLegalBasisLegalRequirement,
        essentialGroupId,
        template,
        isGcm,
        isGcmShowRecommandationsWithoutConsent,
        isBannerLessConsent,
    } = useFormService();
    const [ref, setRef] = useState<HTMLParagraphElement>();

    return (
        <Form.Item<FormServiceValueProps>
            noStyle
            shouldUpdate={(prevValues, nextValues) =>
                prevValues.group !== nextValues.group ||
                prevValues.legalBasis !== nextValues.legalBasis ||
                `${prevValues.codeOptIn}|${prevValues.codeOptOut}|${prevValues.codeOnPageLoad}` !==
                    `${nextValues.codeOptIn}|${nextValues.codeOptOut}|${nextValues.codeOnPageLoad}`
            }
        >
            {({ getFieldValue }) => {
                const isEssentialGroup = getFieldValue("group") === essentialGroupId;
                const legalBasis = getFieldValue("legalBasis") as EServiceTemplateLegalBasis;

                return (
                    <Form.Item<FormServiceValueProps> label={__("Legal basis")} required>
                        <Form.Item name="legalBasis" noStyle rules={[{ required: true }]}>
                            <Field
                                disabled={isEssentialGroup}
                                overwriteValue={
                                    isEssentialGroup && !allowLegalBasisLegalRequirement
                                        ? EServiceTemplateLegalBasis.LegitimateInterest
                                        : undefined
                                }
                            />
                        </Form.Item>
                        <p className="description" ref={setRef}>
                            <FormValueDifferFromTemplateTag
                                form="service"
                                valueName="legalBasis"
                                widthOfRef={ref}
                                style={{ marginBottom: 3 }}
                                renderDiff={(value) => <Field disabled value={value} />}
                            />
                            {_i(
                                __(
                                    'Services can be used on various legal bases according to {{aGdpr}}Art. 6 GDPR{{/aGdpr}} for procession personal data and the national implementations of {{aEP}}ePrivacy Directive (Directive 2009/136/EC) Recital 66{{/aEP}} for storing or accessing cookies or cookie like information. "Consent" means that the user must explicitly agree to the service (opt-in). "Legitimate interest" means that your interest as a website operator prevails to use the service and the user must explicitly disagree (opt-out). Unless it is an essential service. Then an objection is not possible. {{strong}}A legitimate interest exists only in rare cases and only for data processing. If you are not sure, it is better to obtain consent to be on the safe side.{{/strong}}',
                                ),
                                {
                                    strong: <strong />,
                                    aGdpr: (
                                        <a
                                            href={__("https://gdpr-text.com/read/article-6/")}
                                            target="_blank"
                                            rel="noreferrer"
                                        />
                                    ),
                                    aEP: (
                                        <a
                                            href={__("https://devowl.io/go/eu-directive-2009-136-ec")}
                                            target="_blank"
                                            rel="noreferrer"
                                        />
                                    ),
                                },
                            )}
                        </p>
                        <Notices
                            notices={[
                                {
                                    message:
                                        isEssentialGroup &&
                                        !allowLegalBasisLegalRequirement &&
                                        __(
                                            'Your service is currently grouped as "Essential". This group implies the legitimate interest, with the only difference that this service cannot be opted out.',
                                        ),
                                    severity: "info",
                                },
                                {
                                    message: template?.legalBasisNotice,
                                    severity: "info",
                                },
                                {
                                    message:
                                        isGcm &&
                                        isGcmShowRecommandationsWithoutConsent &&
                                        legalBasis === EServiceTemplateLegalBasis.Consent &&
                                        /gtag\(|gtag=/.test(
                                            `${getFieldValue("codeOptIn")}${getFieldValue("codeOptOut")}${getFieldValue(
                                                "codeOnPageLoad",
                                            )}`,
                                        ) &&
                                        _i(
                                            __(
                                                "You have activated Google Consent Mode and agreed to the recommendations for the use of Google services without consent. At the same time, you allow this service to be loaded only after consent has been obtained. Please check whether you wish to use these services on your website {{strong}}on the basis of a legitimate interest{{/strong}} (even before Google receiving consent into consent types accordance with Google Consent Mode and therefore e.g. not setting advertising cookies)!",
                                            ),
                                            { strong: <strong /> },
                                        ),
                                    severity: "warning",
                                },
                                {
                                    message:
                                        isBannerLessConsent &&
                                        !isEssentialGroup &&
                                        legalBasis === EServiceTemplateLegalBasis.LegitimateInterest &&
                                        _i(
                                            __(
                                                "You have decided to obtain consent without cookie banners (banner-less consent) on your website. This means that when your website visitors visit your website for the first time, they will not know that you use this service on the basis of a legitimate interest and can object to it. They will need to read your cookie policy or privacy policy to find out. Check whether there really is a legitimate interest in the legal sense according to {{a}}Art. 6 (1) (f) GDPR{{/a}}, which is only given in rare cases!",
                                            ),
                                            {
                                                a: (
                                                    <a
                                                        href={__("https://gdpr-text.com/read/article-6/")}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                    />
                                                ),
                                            },
                                        ),
                                    severity: "warning",
                                },
                            ]}
                        />
                    </Form.Item>
                );
            }}
        </Form.Item>
    );
};

export { FormServiceFieldGeneralLegalBasis };
