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

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

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

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

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

    return (
        <Form.Item<FormServiceValueProps>
            noStyle
            shouldUpdate={(prevValues, nextValues) =>
                prevValues.group !== nextValues.group ||
                prevValues.isProviderCurrentWebsite !== nextValues.isProviderCurrentWebsite ||
                JSON.stringify(prevValues.dataProcessingInCountries) !==
                    JSON.stringify(nextValues.dataProcessingInCountries) ||
                JSON.stringify(prevValues.dataProcessingInCountriesSpecialTreatments) !==
                    JSON.stringify(nextValues.dataProcessingInCountriesSpecialTreatments)
            }
        >
            {({ getFieldValue }) => {
                const unsafeCountries = getFieldValue("isProviderCurrentWebsite")
                    ? []
                    : calculateSafetyMechanismsFromSpecialTreatments({
                          predefinedDataProcessingInSafeCountriesLists,
                          territorialLegalBasis,
                          isDataProcessingInUnsafeCountries: true,
                          service: {
                              dataProcessingInCountries: getFieldValue("dataProcessingInCountries"),
                              dataProcessingInCountriesSpecialTreatments: getFieldValue(
                                  "dataProcessingInCountriesSpecialTreatments",
                              ),
                          },
                      }).filter((mechanism) => mechanism.startsWith("D"));

                return (
                    <Form.Item<FormServiceValueProps> label={__("Data processing in countries")}>
                        <Form.Item<FormServiceValueProps> name="dataProcessingInCountries" noStyle>
                            <Select
                                mode="multiple"
                                showSearch
                                optionFilterProp="children"
                                maxTagCount="responsive"
                                allowClear
                            >
                                {Object.keys(iso3166OneAlpha2).map((code) => (
                                    <Select.Option value={code} key={code}>
                                        {iso3166OneAlpha2[code]}
                                    </Select.Option>
                                ))}
                            </Select>
                        </Form.Item>
                        <p className="description" ref={setRef}>
                            <FormValueDifferFromTemplateTag
                                form="service"
                                valueName="dataProcessingInCountries"
                                widthOfRef={ref}
                                difference={diffByJsonStringify}
                                renderDiff={(value) => (
                                    <Select mode="multiple" disabled value={value}>
                                        {Object.keys(iso3166OneAlpha2).map((code) => (
                                            <Select.Option value={code} key={code}>
                                                {iso3166OneAlpha2[code]}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                )}
                            />
                            {__(
                                "Data is usually processed in the countries where the service has its headquarter or servers. You should check with your service provider where your users' data is processed.",
                            )}
                        </p>
                        {unsafeCountries.length > 0 && getFieldValue("group") === essentialGroupId && (
                            <Notices
                                notices={[
                                    {
                                        message: __(
                                            "A transfer of personal data (e.g. IP address of the website visitor) to third countries that are unsafe in terms of data protection law (%s), is only permitted with prior consent. Consequently, such a service can never be essential under data protection law, since essential services are used on a different (in the case, non-existent) legal basis. In practice, however, it will not always be possible to avoid such use.",
                                            unsafeCountries.map((country) => iso3166OneAlpha2[country]).join(", "),
                                        ),
                                        severity: "warning",
                                    },
                                ]}
                            />
                        )}
                    </Form.Item>
                );
            }}
        </Form.Item>
    );
};

export { FormServiceFieldGeneralDataProcessingCountries };
