import {
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import {
  hasAnalyticsConfiguration,
  privacyConfig,
} from "./privacy-config";
import {
  AnalyticsConsentContext,
  type AnalyticsPreferenceValue,
} from "./analytics-consent-context";

const SCRIPT_ID = "plimi-umami-script";
const UMAMI_DISABLED_KEY = "umami.disabled";

function analyticsEnabledInitially(): boolean {
  return window.localStorage.getItem(UMAMI_DISABLED_KEY) !== "1";
}

function removeAnalyticsScript() {
  document.getElementById(SCRIPT_ID)?.remove();
}

function loadAnalyticsScript() {
  if (!hasAnalyticsConfiguration || document.getElementById(SCRIPT_ID)) return;

  const script = document.createElement("script");
  script.id = SCRIPT_ID;
  script.defer = true;
  script.src = privacyConfig.analyticsScriptUrl;
  script.dataset.websiteId = privacyConfig.analyticsWebsiteId;
  script.dataset.hostUrl = privacyConfig.analyticsHostUrl;
  script.dataset.domains = new URL(privacyConfig.siteUrl).hostname;
  script.dataset.doNotTrack = "true";
  script.dataset.excludeSearch = "true";
  script.dataset.excludeHash = "true";
  document.head.appendChild(script);
}

export function AnalyticsConsentProvider({
  children,
}: {
  children: ReactNode;
}) {
  const [enabled, setEnabled] = useState(analyticsEnabledInitially);

  useEffect(() => {
    if (enabled) {
      loadAnalyticsScript();
    } else {
      removeAnalyticsScript();
    }
  }, [enabled]);

  const value = useMemo<AnalyticsPreferenceValue>(
    () => ({
      enabled,
      disableAnalytics: () => {
        window.localStorage.setItem(UMAMI_DISABLED_KEY, "1");
        setEnabled(false);
        window.location.reload();
      },
      enableAnalytics: () => {
        window.localStorage.removeItem(UMAMI_DISABLED_KEY);
        setEnabled(true);
        window.location.reload();
      },
      toggleAnalytics: () => {
        if (enabled) {
          window.localStorage.setItem(UMAMI_DISABLED_KEY, "1");
        } else {
          window.localStorage.removeItem(UMAMI_DISABLED_KEY);
        }
        setEnabled(!enabled);
        window.location.reload();
      },
    }),
    [enabled]
  );

  return (
    <AnalyticsConsentContext.Provider value={value}>
      {children}
    </AnalyticsConsentContext.Provider>
  );
}
