import { createRef, useMemo, useRef } from 'react';

import type { CheckboxApi } from '~/src/components/Checkbox';
import type {
  MarketingConsentCountry,
  MarketingConsentOptIn,
} from '~/src/lib/privacy';
import type { ReactNode, RefObject } from 'react';
import type { CheckboxesConfig } from './types';

import locales from '~/locales/fragments/marketingConsent';
import Checkbox from '~/src/components/Checkbox';
import Link from '~/src/components/Link2';
import { PORTUGAL, SPAIN } from '~/src/lib/country/countryCodes';
import { toPublicEndpoint } from '~/src/lib/getPublicEndpoint';
import { useI18n, useI18nStatic } from '~/src/lib/i18n';
import {
  getLegalName,
  REQUIRED_MARKETING_OPT_IN_CONFIG,
} from '~/src/lib/privacy';
import { DEFAULT_CHECKED_COUNTRIES_CONFIG } from './constants';
import {
  getCountryBasedOptInI18nKey,
  getMarketingConsentConfig,
} from './utils';

interface CheckboxConfigProps {
  country: MarketingConsentCountry;
  artistName: string;
  checkboxesConfig?: CheckboxesConfig;
}

interface OptInCheckboxes {
  optInCheckboxApiRefs: RefObject<
    Record<string, RefObject<CheckboxApi | null>>
  >;

  optInCheckboxes: Record<MarketingConsentOptIn, ReactNode>;
  optOutCheckboxes: Partial<Record<MarketingConsentOptIn, ReactNode>>;

  optInConfig: MarketingConsentOptIn[];
  optOutConfig: MarketingConsentOptIn[];
}

const COUNTRIES_WITHOUT_CHECKBOX_LABELS: MarketingConsentCountry[] = [
  SPAIN,
  PORTUGAL,
];

export const useMarketingConsent = ({
  country,
  artistName,
  checkboxesConfig,
}: CheckboxConfigProps): OptInCheckboxes => {
  const { t, tx } = useI18nStatic<'marketingConsent'>(locales);
  const { t: tApp } = useI18n('app');

  const legalName = getLegalName(country);

  const { optInConfig, optOutConfig } = useMemo(
    () => getMarketingConsentConfig(country),
    [country]
  );

  // Resolve each opt-in's required / pre-checked state from the country-driven
  // config, escalated (never relaxed) by any consumer-provided override.
  const resolveOptInState = (key: MarketingConsentOptIn) => ({
    isRequired:
      REQUIRED_MARKETING_OPT_IN_CONFIG[key]?.includes(country) ||
      checkboxesConfig?.[key]?.isRequired,
    isInitiallyChecked:
      DEFAULT_CHECKED_COUNTRIES_CONFIG[key]?.includes(country) ||
      checkboxesConfig?.[key]?.isInitiallyChecked,
  });

  const emailMarketingState = resolveOptInState('emailMarketing');
  const marketingProfilingState = resolveOptInState('marketingProfiling');
  const advertisingProfilingState = resolveOptInState('advertisingProfiling');
  const analyticsProfilingState = resolveOptInState('analyticsProfiling');
  const dataSharingState = resolveOptInState('dataSharing');

  const isCheckboxLabelHidden =
    optOutConfig.length > 0 ||
    COUNTRIES_WITHOUT_CHECKBOX_LABELS.includes(country);

  const optInCheckboxApiRefs = useRef<{
    emailMarketing: RefObject<CheckboxApi | null>;
    marketingProfiling: RefObject<CheckboxApi | null>;
    advertisingProfiling: RefObject<CheckboxApi | null>;
    analyticsProfiling: RefObject<CheckboxApi | null>;
    dataSharing: RefObject<CheckboxApi | null>;
  }>({
    emailMarketing: createRef(),
    marketingProfiling: createRef(),
    advertisingProfiling: createRef(),
    analyticsProfiling: createRef(),
    dataSharing: createRef(),
  });

  const privacyLink = ({ children }) => (
    <Link
      testId="dataSharingPrivacyLink"
      withHoverStyle
      isUnderlined
      href={toPublicEndpoint(`/privacy/sme/${country.toLowerCase()}`)}
    >
      {children}
    </Link>
  );

  const optInCheckboxes = useMemo(
    () => ({
      emailMarketing: (
        <Checkbox
          key="emailMarketingOptIn"
          apiRef={optInCheckboxApiRefs.current.emailMarketing}
          testId="emailMarketingOptInCheckbox"
          name="emailMarketingOptIn"
          title={
            isCheckboxLabelHidden
              ? undefined
              : t('emailMarketingLabel', { artist: artistName })
          }
          description={
            country === 'ES' ? (
              <>
                He leído y acepto la{' '}
                {privacyLink({ children: 'Política de Privacidad' })} y, en
                consecuencia, deseo recibir información sobre el {artistName} a
                través de correo electrónico, SMS, Whatsapp u otros medios
                electrónicos.
              </>
            ) : country === 'PT' ? (
              <>
                Li a {privacyLink({ children: 'Política de Privacidade' })} e
                desejo receber informação sobre o {artistName} através de
                correio eletrónico, SMS, Whatsapp ou outros meios eletrónicos.
              </>
            ) : (
              tx(getCountryBasedOptInI18nKey('emailMarketingOptIn', country), {
                artistName,
                legalName,
                privacyLink,
              })
            )
          }
          isRequired={emailMarketingState.isRequired}
          isInitiallyChecked={emailMarketingState.isInitiallyChecked}
          validationMessage={
            emailMarketingState.isRequired ? tApp('errors.required') : undefined
          }
        />
      ),
      marketingProfiling: (
        <Checkbox
          key="marketingProfilingOptIn"
          apiRef={optInCheckboxApiRefs.current.marketingProfiling}
          testId="marketingProfilingOptInCheckbox"
          name="marketingProfilingOptIn"
          title={
            isCheckboxLabelHidden
              ? undefined
              : t(
                  getCountryBasedOptInI18nKey(
                    'marketingProfilingLabel',
                    country
                  ),
                  { legalName }
                )
          }
          description={
            country === 'ES' ? (
              <>
                Quiero recibir información comercial, concursos, material
                promocional de {legalName} y sus artistas a través de correo
                electrónico, SMS, Whatsapp u otros medios electrónicos.
              </>
            ) : country === 'PT' ? (
              <>
                Quero receber informações comerciais, concursos, material
                promocional da {legalName} e dos seus artistas através de
                correio eletrónico, SMS, Whatsapp ou outros meios eletrónicos.
              </>
            ) : (
              t(
                getCountryBasedOptInI18nKey('marketingProfilingOptIn', country),
                { legalName }
              )
            )
          }
          isRequired={marketingProfilingState.isRequired}
          isInitiallyChecked={marketingProfilingState.isInitiallyChecked}
          validationMessage={
            marketingProfilingState.isRequired
              ? tApp('errors.required')
              : undefined
          }
        />
      ),
      advertisingProfiling: (
        <Checkbox
          key="advertisingProfilingOptIn"
          apiRef={optInCheckboxApiRefs.current.advertisingProfiling}
          testId="advertisingProfilingOptInCheckbox"
          name="advertisingProfilingOptIn"
          title={
            isCheckboxLabelHidden ? undefined : t('advertisingProfilingLabel')
          }
          description={t(
            getCountryBasedOptInI18nKey('advertisingProfilingOptIn', country),
            { legalName }
          )}
          isRequired={advertisingProfilingState.isRequired}
          isInitiallyChecked={advertisingProfilingState.isInitiallyChecked}
          validationMessage={
            advertisingProfilingState.isRequired
              ? tApp('errors.required')
              : undefined
          }
        />
      ),
      analyticsProfiling: (
        <Checkbox
          key="analyticsProfilingOptIn"
          apiRef={optInCheckboxApiRefs.current.analyticsProfiling}
          testId="analyticsProfilingOptInCheckbox"
          name="analyticsProfilingOptIn"
          title={
            isCheckboxLabelHidden ? undefined : t('analyticsProfilingLabel')
          }
          description={t(
            getCountryBasedOptInI18nKey('analyticsProfilingOptIn', country),
            { artistName, legalName }
          )}
          isRequired={analyticsProfilingState.isRequired}
          isInitiallyChecked={analyticsProfilingState.isInitiallyChecked}
          validationMessage={
            analyticsProfilingState.isRequired
              ? tApp('errors.required')
              : undefined
          }
        />
      ),
      dataSharing: (
        <Checkbox
          key="dataSharingOptIn"
          apiRef={optInCheckboxApiRefs.current.dataSharing}
          testId="dataSharingOptInCheckbox"
          name="dataSharingOptIn"
          title={
            isCheckboxLabelHidden
              ? undefined
              : t(getCountryBasedOptInI18nKey('dataSharingLabel', country), {
                  artistName,
                  legalName,
                })
          }
          description={tx(
            getCountryBasedOptInI18nKey('dataSharingOptIn', country),
            {
              artistName,
              legalName,
              privacyLink,
              companiesLink: ({ children }) => (
                <Link
                  href={toPublicEndpoint('/privacy/companies')}
                  inNewTab
                  isUnderlined
                  withHoverStyle
                >
                  {children}
                </Link>
              ),
            }
          )}
          isRequired={dataSharingState.isRequired}
          isInitiallyChecked={dataSharingState.isInitiallyChecked}
          validationMessage={
            dataSharingState.isRequired ? tApp('errors.required') : undefined
          }
        />
      ),
    }),
    []
  );

  const optOutCheckboxes = useMemo(
    () => ({
      emailMarketing: (
        <Checkbox
          key="emailMarketingOptOut"
          testId="emailMarketingOptOutCheckbox"
          name="emailMarketingOptOut"
          description={t('emailMarketingOptOut')}
        />
      ),
    }),
    []
  );

  return {
    optInCheckboxApiRefs,
    optInCheckboxes,
    optOutCheckboxes,
    optInConfig,
    optOutConfig,
  };
};
