import { Checkbox, Form, Tooltip } from "antd";

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

import { useFormTcfVendor } from "../../../../../contexts/formTcfVendor.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { useServiceDataProcessingCountriesSpecialTreatments } from "../../../../../hooks/useServiceDataProcessingCountriesSpecialTreatments.js";
import { useTerritorialLegalBasisArticles } from "../../../../../hooks/useTerritorialLegalBasisArticles.js";

import type { FormTcfVendorValueProps } from "../../../../../types/formTcfVendor.js";
import type { FC } from "react";

const FormTcfVendorFieldGeneralDataProcessingInCountriesSpecialTreatments: FC = () => {
    const { __, _i } = useI18n();
    const {
        iso3166OneAlpha2,
        territorialLegalBasis,
        predefinedDataProcessingInSafeCountriesLists,
        vendor: { additionalInformation },
    } = useFormTcfVendor();

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

    return (
        <Form.Item<FormTcfVendorValueProps>
            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 FormTcfVendorValueProps["dataProcessingInCountries"];
                const dataProcessingInCountriesSpecialTreatments = getFieldValue(
                    "dataProcessingInCountriesSpecialTreatments",
                ) as FormTcfVendorValueProps["dataProcessingInCountriesSpecialTreatments"];
                const { unsafeCountries, allowedSpecialTreatments } = calculateSafetyMechanismsFromSpecialTreatments({
                    territorialLegalBasis,
                    predefinedDataProcessingInSafeCountriesLists,
                    service: {
                        dataProcessingInCountries,
                        dataProcessingInCountriesSpecialTreatments,
                    },
                });

                const specialTreatmentOptions = specialTreatments
                    .filter(({ value }) => allowedSpecialTreatments.indexOf(value) > -1)
                    .map((obj) => {
                        const hasScssTransferMechanism =
                            additionalInformation?.transferMechanisms?.indexOf("SCCs") > -1;

                        // TCF supports also Standard Contractual clauses, so we need to force to use the SCCs and the user should not be able to uncheck it
                        return obj.value ===
                            EServiceTemplateDataProcessingInCountriesSpecialTreatment.StandardContractualClauses
                            ? {
                                  ...obj,
                                  disabled: hasScssTransferMechanism,
                                  label: hasScssTransferMechanism ? (
                                      <Tooltip
                                          title={__(
                                              "The vendor states that standard contractual clauses must be concluded with it in any case. Please make sure that you have a corresponding contract with him!",
                                          )}
                                          overlayStyle={{ maxWidth: 500 }}
                                          placement="bottomLeft"
                                      >
                                          {obj.label}
                                      </Tooltip>
                                  ) : (
                                      obj.label
                                  ),
                              }
                            : obj;
                    });

                return (
                    <Form.Item<FormTcfVendorValueProps>
                        label={__("Safety mechanisms for data transmission")}
                        style={{
                            display: specialTreatmentOptions.length === 0 ? "none" : undefined,
                        }}
                    >
                        <p className="description" 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<FormTcfVendorValueProps> name="dataProcessingInCountriesSpecialTreatments" noStyle>
                            <Checkbox.Group options={specialTreatmentOptions} />
                        </Form.Item>
                    </Form.Item>
                );
            }}
        </Form.Item>
    );
};

export { FormTcfVendorFieldGeneralDataProcessingInCountriesSpecialTreatments };
