import { Fragment, useMemo } from "react";

import { reactNl2Br } from "@devowl-wp/react-utils";

import { CookieProperty } from "./cookieProperty.js";
import { CookiePropertyDataTransmission } from "./cookiePropertyDataTransmission.js";
import { CookiePropertyListLessRelevant } from "./cookiePropertyListLessRelevant.js";
import { CookiePropertyTechnicalDefinitionsTable } from "./cookiePropertyTechnicalDefinitionsTable.js";
import { useAppropriateSafeguards } from "../../../hooks/common/useAppropriateSafeguards.js";
import { useBannerOrBlocker } from "../../../hooks/useBannerOrBlocker.js";
import { useLegalLinks } from "../../../hooks/useLegalLinks.js";
import { GcmConsentType } from "../gcm/consentType.js";

import type { VisualService } from "../../../types/service.js";
import type { FC } from "react";

const CookiePropertyList: FC<{ cookie: VisualService; isEssentialGroup?: boolean; isDisabled?: boolean }> = ({
    cookie: {
        name,
        purpose,
        isProviderCurrentWebsite,
        provider,
        providerContact = {},
        providerPrivacyPolicyUrl,
        providerLegalNoticeUrl,
        legalBasis,
        dataProcessingInCountries,
        dataProcessingInCountriesSpecialTreatments,
        isEmbeddingOnlyExternalResources,
        technicalDefinitions,
        codeDynamics,
        googleConsentModeConsentTypes,
    },
    isEssentialGroup,
    isDisabled,
}) => {
    const { i18n, iso3166OneAlpha2, websiteOperator, isGcm, designVersion } = useBannerOrBlocker();
    const { deprecated: i18nDeprecated, legalBasis: i18nLegalBasis } = i18n;

    const { dataProcessingInUnsafeCountries, appropriateSafeguards } = useAppropriateSafeguards({
        dataProcessingInCountries,
        specialTreatments: dataProcessingInCountriesSpecialTreatments,
    });

    // Calculate provider-specific details
    const { legalNotice, privacyPolicy, contactForm } = useLegalLinks();
    const providerData = useMemo(() => {
        if (isProviderCurrentWebsite && websiteOperator) {
            const { address, country, contactEmail, contactPhone } = websiteOperator;
            return {
                provider: [address, iso3166OneAlpha2[country] || country].filter(Boolean).join(", "),
                contact: {
                    email: contactEmail,
                    phone: contactPhone,
                    link: contactForm,
                },
                legalNoticeUrl: legalNotice === false ? "" : legalNotice.url,
                privacyPolicyUrl: privacyPolicy === false ? "" : privacyPolicy.url,
            };
        }

        return {
            provider,
            contact: providerContact,
            privacyPolicyUrl: providerPrivacyPolicyUrl,
            legalNoticeUrl: providerLegalNoticeUrl,
        };
    }, [
        isProviderCurrentWebsite,
        provider,
        providerContact,
        providerPrivacyPolicyUrl,
        providerLegalNoticeUrl,
        websiteOperator,
        legalNotice,
        privacyPolicy,
        contactForm,
    ]);

    const hasProviderContact = useMemo(
        () => Object.values(providerData.contact).filter(Boolean).length > 0,
        [providerData.contact],
    );

    const legalBasisValue = useMemo(() => {
        const isLegalBasisLegalRequirement = legalBasis === "legal-requirement";
        const isLegalBasisLegitimateInterest = legalBasis === "legitimate-interest" || isEssentialGroup;
        if (designVersion <= 11) {
            return isLegalBasisLegalRequirement
                ? i18nDeprecated.legalRequirement
                : isLegalBasisLegitimateInterest
                  ? i18n.legitimateInterest
                  : i18n.consent;
        } else {
            const {
                consentPersonalData,
                consentStorage,
                legitimateInterestPersonalData,
                legitimateInterestStorage,
                legalRequirementPersonalData,
            } = i18nLegalBasis;

            return [
                // Personal data
                isLegalBasisLegalRequirement
                    ? legalRequirementPersonalData
                    : isLegalBasisLegitimateInterest
                      ? legitimateInterestPersonalData
                      : consentPersonalData,
                // Storage
                !isEmbeddingOnlyExternalResources &&
                    (isLegalBasisLegalRequirement
                        ? legitimateInterestStorage
                        : isLegalBasisLegitimateInterest
                          ? legitimateInterestStorage
                          : consentStorage),
            ]
                .filter(Boolean)
                .join(", ");
        }
    }, [designVersion, legalBasis, isEssentialGroup, i18nLegalBasis, isEmbeddingOnlyExternalResources]);

    return (
        <Fragment>
            {!!purpose && <CookieProperty label={i18n.purpose} value={reactNl2Br(purpose)} />}
            <CookieProperty label={i18n.legalBasis.label} value={legalBasisValue} />
            {isGcm && googleConsentModeConsentTypes.length > 0 && (
                <CookieProperty label={i18n.gcm.dataProcessingInService} printValueAs="empty">
                    <div style={{ display: "inline-block" }}>
                        <CookieProperty printValueAs="empty">
                            {googleConsentModeConsentTypes.map((type) => (
                                <GcmConsentType key={type} type={type} isDisabled={isDisabled} />
                            ))}
                        </CookieProperty>
                    </div>
                </CookieProperty>
            )}
            <CookieProperty label={i18n.provider} value={providerData.provider}>
                {hasProviderContact && (
                    <Fragment>
                        <CookieProperty
                            label={i18n.providerContactPhone}
                            value={providerData.contact.phone}
                            printValueAs="phone"
                        />
                        <CookieProperty
                            label={i18n.providerContactEmail}
                            value={providerData.contact.email}
                            printValueAs="mail"
                        />
                        <CookieProperty label={i18n.providerContactLink} value={providerData.contact.link} />
                    </Fragment>
                )}
            </CookieProperty>
            <CookieProperty label={i18n.providerPrivacyPolicyUrl} value={providerData.privacyPolicyUrl} />
            <CookieProperty label={i18n.providerLegalNoticeUrl} value={providerData.legalNoticeUrl} />
            {designVersion < 10 && dataProcessingInUnsafeCountries.length > 0 && (
                <CookieProperty
                    label={i18nDeprecated.dataProcessingInUnsafeCountries}
                    value={dataProcessingInUnsafeCountries.join(", ")}
                />
            )}
            {designVersion < 10 && appropriateSafeguards.length > 0 && (
                <CookieProperty label={i18nDeprecated.appropriateSafeguard} value={appropriateSafeguards.join(", ")} />
            )}
            <CookiePropertyListLessRelevant
                expandable={designVersion > 9}
                labelModifications={{ [i18n.technicalCookieName]: i18n.technicalCookieDefinitions }}
                groupLabel={name}
            >
                {designVersion > 9 && (
                    <CookiePropertyDataTransmission
                        dataProcessingInCountries={dataProcessingInCountries}
                        dataProcessingInCountriesSpecialTreatments={dataProcessingInCountriesSpecialTreatments}
                    />
                )}
                {!isEmbeddingOnlyExternalResources && (
                    <CookiePropertyTechnicalDefinitionsTable
                        codeDynamics={codeDynamics}
                        definitions={technicalDefinitions}
                    />
                )}
            </CookiePropertyListLessRelevant>
        </Fragment>
    );
};

export { CookiePropertyList };
