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

import { calculateSafetyMechanismsFromSpecialTreatments } from "@devowl-wp/react-cookie-banner";
import { jsxJoin } from "@devowl-wp/react-utils";

import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { useServiceDataProcessingCountriesSpecialTreatments } from "../../../../../hooks/useServiceDataProcessingCountriesSpecialTreatments.js";
import { useTerritorialLegalBasisArticles } from "../../../../../hooks/useTerritorialLegalBasisArticles.js";
import { FormValueDifferFromTemplateTag, diffByJsonStringify } from "../../../valueDifferFromTemplateTag.js";

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

const FormServiceFieldGeneralDataProcessingCountriesSpecialTreatment: FC = () => {
    const { __, _i } = useI18n();
    const { iso3166OneAlpha2, territorialLegalBasis, predefinedDataProcessingInSafeCountriesLists } = useFormService();
    const [ref, setRef] = useState<HTMLDivElement>();

    const specialTreatments = useServiceDataProcessingCountriesSpecialTreatments({
        __,
        _i,
        predefinedDataProcessingInSafeCountriesLists,
        iso3166OneAlpha2,
        territorialLegalBasis,
    });
    const { dataProcessingInUnsafeCountriesArticles, dataProcessingInUnsafeCountriesArticlesLinks } =
        useTerritorialLegalBasisArticles({
            predefinedDataProcessingInSafeCountriesLists,
            iso3166OneAlpha2,
        })(territorialLegalBasis);

    return (
        <Form.Item<FormServiceValueProps>
            noStyle
            shouldUpdate={(prevValues, nextValues) =>
                JSON.stringify(prevValues.dataProcessingInCountries) !==
                    JSON.stringify(nextValues.dataProcessingInCountries) ||
                JSON.stringify(prevValues.dataProcessingInCountriesSpecialTreatments) !==
                    JSON.stringify(nextValues.dataProcessingInCountriesSpecialTreatments)
            }
        >
            {({ getFieldValue }) => {
                const dataProcessingInCountries = getFieldValue(
                    "dataProcessingInCountries",
                ) as FormServiceValueProps["dataProcessingInCountries"];
                const dataProcessingInCountriesSpecialTreatments = getFieldValue(
                    "dataProcessingInCountriesSpecialTreatments",
                ) as FormServiceValueProps["dataProcessingInCountriesSpecialTreatments"];
                const { unsafeCountries, allowedSpecialTreatments } = calculateSafetyMechanismsFromSpecialTreatments({
                    territorialLegalBasis,
                    predefinedDataProcessingInSafeCountriesLists,
                    service: {
                        dataProcessingInCountries,
                        dataProcessingInCountriesSpecialTreatments,
                    },
                });

                const specialTreatmentOptions = specialTreatments.filter(
                    ({ value }) => allowedSpecialTreatments.indexOf(value) > -1,
                );

                return (
                    <Form.Item<FormServiceValueProps>
                        label={__("Safety mechanisms for data transmission")}
                        style={{
                            display: allowedSpecialTreatments.length === 0 ? "none" : undefined,
                        }}
                    >
                        <p className="description" ref={setRef} style={{ margin: "0px 0px 10px 0px" }}>
                            {_i(
                                __(
                                    "You have selected countries which are considered as unsafe (%s). If you activate one of this safety mechanisms, you do not ask for consent according to {{article/}}, if this kind of consent is activated at all in the settings.",
                                    unsafeCountries.map((country) => iso3166OneAlpha2[country]).join(", "),
                                ),
                                {
                                    article: jsxJoin(
                                        dataProcessingInUnsafeCountriesArticles.map((article, i) => {
                                            return (
                                                <a
                                                    key={article}
                                                    href={dataProcessingInUnsafeCountriesArticlesLinks[i]}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                >
                                                    {article}
                                                </a>
                                            );
                                        }),
                                        __(" or "),
                                    ),
                                },
                            )}
                        </p>
                        <Form.Item<FormServiceValueProps> name="dataProcessingInCountriesSpecialTreatments" noStyle>
                            <Checkbox.Group options={specialTreatmentOptions} />
                        </Form.Item>
                        <FormValueDifferFromTemplateTag
                            form="service"
                            valueName="dataProcessingInCountriesSpecialTreatments"
                            widthOfRef={ref}
                            style={{ marginTop: 10 }}
                            difference={(oldValue, newValue) =>
                                diffByJsonStringify(
                                    oldValue.filter((e) => allowedSpecialTreatments.indexOf(e) > -1),
                                    newValue.filter((e) => allowedSpecialTreatments.indexOf(e) > -1),
                                )
                            }
                            renderDiff={(value) => {
                                return <Checkbox.Group options={specialTreatmentOptions} value={value} disabled />;
                            }}
                        />
                    </Form.Item>
                );
            }}
        </Form.Item>
    );
};

export { FormServiceFieldGeneralDataProcessingCountriesSpecialTreatment };
