'use client';

import React, { createContext, useEffect, useState, ReactNode } from "react";

export const COOKIE_PREFERENCE = "cookie_preference";

const getCookie = (name: string) => {
  if (typeof window !== "undefined") {
    let value = `; ${document.cookie}`;
    let parts: string[] = value.split(`; ${name}=`);

    if (parts.length === 2) {
      // @ts-ignore
      return parts.pop().split(";").shift();
    }
  }

  return false;
};

export type CategoryType = {
  key: string;
  label: string;
  caption: string;
  enabled: boolean;
  disabled?: boolean;
};

export const initialPreferences: CategoryType[] = [
  {
    key: "necessary",
    label: "Necessary",
    caption: "The website cannot function properly without these cookies.",
    enabled: true,
    disabled: true,
  },
  {
    key: "statistics",
    label: "Statistics (optional)",
    caption:
      "Collecting and reporting information anonymously about how visitors interact with the website.",
    enabled: false,
  },
];

export const CookieConsent = createContext<{
  shouldShowConsent: Boolean;
  preferences: CategoryType[];
  update: Function;
  close: Function;
  open: Function;
}>({
  shouldShowConsent: false,
  preferences: initialPreferences,
  update: () => {},
  close: () => {},
  open: () => {},
});

export const CookieConsentContextProvider = ({
  children,
  initialPreferences
}: {
  children: ReactNode;
  initialPreferences: CategoryType[];
}) => {
  const [shouldShowConsent, setShouldShowConsent] = useState<boolean>(false);
  const [preferences, setPreferences] = useState<CategoryType[]>(initialPreferences);

  const update = ({ updatedPreferences = [], shouldShowConsent = false }) => {
    setPreferences(updatedPreferences);
    setShouldShowConsent(shouldShowConsent);
    storePreferences(updatedPreferences);
  };

  const storePreferences = (prefs: CategoryType[]) => {
    document.cookie = `${COOKIE_PREFERENCE}=${JSON.stringify(
      prefs,
    )}; path=/; max-age=${60 * 60 * 24 * 90};`;
  };

  const open = () => setShouldShowConsent(true);

  const close = () => setShouldShowConsent(false);

  /**
   * First render, if no cookie set
   * show consent and set default preferences.
   */
  useEffect(() => {
    const storedPreferences = getCookie(COOKIE_PREFERENCE);

    if (!storedPreferences) {
      setShouldShowConsent(true);
    } else {
      try {
        const parsedPreferences = JSON.parse(storedPreferences);
        if (Array.isArray(parsedPreferences)) {
          setPreferences(parsedPreferences);
        }
      } catch {
        setShouldShowConsent(true);
      }
    }

    if (typeof window !== "undefined") {
      // @ts-ignore
      window.toggleConsent = () => setShouldShowConsent(!shouldShowConsent);
    }
  }, []);

  return (
    <CookieConsent.Provider
      value={{ shouldShowConsent, preferences, update, close, open }}
    >
      {children}
    </CookieConsent.Provider>
  );
};
