"use client";

import styles from "./CookieConsent.module.css";
import { MouseEvent, useState } from "react";
import useCookieContext from "@/hooks/useCookieContext";
import NextLink from "next/link";

const CookieConsent = () => {
  const cookieContext = useCookieContext();
  const [toggleSettings, setToggleSettings] = useState(false);

  const handleToggle = (e: MouseEvent, key: string) => {
    // @ts-ignore
    const preferencesToUpdate = [...cookieContext.preferences];
    const index = preferencesToUpdate.findIndex((pref) => pref.key === key);

    if (
      typeof preferencesToUpdate[index].disabled !== "undefined" &&
      preferencesToUpdate[index].disabled
    ) {
      return;
    }

    if (!index) return;

    preferencesToUpdate[index].enabled = !preferencesToUpdate[index].enabled;

    cookieContext.update({
      shouldShowConsent: true,
      updatedPreferences: preferencesToUpdate,
    });
  };

  const acceptCookies = () => {
    if (toggleSettings) {
      cookieContext.close();
      setToggleSettings(false);
      return;
    }

    const preferencesToUpdate = [...cookieContext.preferences];
    preferencesToUpdate.map((pref, index) => {
      preferencesToUpdate[index].enabled = true;
    });

    cookieContext.update({ updatedPreferences: preferencesToUpdate });

    setToggleSettings(false);
  };

  const declineCookies = () => {
    const preferencesToUpdate = [...cookieContext.preferences];
    preferencesToUpdate.map((pref, index) => {
      if (typeof pref.disabled === "undefined") {
        preferencesToUpdate[index].enabled = false;
      }
    });

    cookieContext.update({ updatedPreferences: preferencesToUpdate });
    setToggleSettings(false);
  };

  return (
    <>
      <div
        className={`${styles.consent} ${
          cookieContext.shouldShowConsent ? "block" : ""
        }`}
      >
        <p className={styles.consent__label}>
          This website uses cookies to improve your browsing experience. Manage
          your{" "}
          <span
            className="text-green hover:underline cursor-pointer"
            onClick={() => setToggleSettings(!toggleSettings)}
          >
            cookie settings
          </span>{" "}
          or view our{" "}
          <NextLink
            className="text-green hover:underline"
            href={"/cookie-policy"}
          >
            cookie policy
          </NextLink>
          .
        </p>
        {toggleSettings && (
          <div className="mb-xs w-full flex flex-col">
            {cookieContext.preferences &&
              cookieContext.preferences.map((category) => (
                <div key={category.key} className={styles.consent__row}>
                  <h6 className={styles.consent__category}>{category.label}</h6>
                  <small>{category.caption}</small>
                  <label
                    htmlFor={category.key}
                    className={`${styles.consent__toggle}${
                      category.disabled ? " opacity-40 cursor-not-allowed" : ""
                    }`}
                    onClick={(e) => handleToggle(e, category.key)}
                  >
                    <input
                      type="checkbox"
                      name={category.key}
                      defaultChecked={category.enabled}
                    />
                    <span
                      className={`${styles.consent__slider} ${
                        category.enabled
                          ? [styles.checked, styles.move].join(" ")
                          : ""
                      }`}
                    />
                  </label>
                </div>
              ))}
          </div>
        )}
        <div className="w-full flex flex-col md:flex-row md:items-center justify-between">
          <button
            className={styles.consent__btn}
            type="button"
            onClick={declineCookies}
          >
            Decline cookies
          </button>
          <button
            className={`${styles.consent__btn} mt-xs md:mt-none md:ms-xs`}
            type="button"
            onClick={acceptCookies}
          >
            Accept cookies
          </button>
        </div>
      </div>
    </>
  );
};

export default CookieConsent;
