import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import Cookies from "js-cookie";
import CryptoJS from "crypto-js";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import Loading from "@/app/[locale]/(protected)/app/projects/loading";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

const MySwal = withReactContent(Swal);

const Toast = MySwal.mixin({
  toast: true,
  position: "top-end",
  showConfirmButton: false,
  timer: 3000,
  timerProgressBar: true,
  didOpen: (toast) => {
    toast.addEventListener("mouseenter", Swal.stopTimer);
    toast.addEventListener("mouseleave", Swal.resumeTimer);
  },
});

export const hexToRGB = (hex: any, alpha?: number): any => {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);

  if (alpha) {
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  } else {
    return `rgb(${r}, ${g}, ${b})`;
  }
};

export function getCookiesDecrypt(param: any) {
  const cookiesEncrypt = Cookies.get(param);
  try {
    if (cookiesEncrypt != undefined) {
      const output = CryptoJS.AES.decrypt(
        cookiesEncrypt.toString(),
        `${param}_EncryptKey@mediahub`
      ).toString(CryptoJS.enc.Utf8);
      if (output.startsWith('"')) {
        return output.slice(1, -1);
      }
      return output;
    }
  } catch (e) {
    console.log("Error", cookiesEncrypt);
  }
}

export function successToast(title: string, text: string) {
  Toast.fire({
    icon: "error",
    title: title,
    text: text,
  });
}

export function setCookiesEncrypt(
  param: string,
  data: any,
  options?: Cookies.CookieAttributes
) {
  // Enkripsi data
  const cookiesEncrypt = CryptoJS.AES.encrypt(
    JSON.stringify(data),
    `${param}_EncryptKey@mediahub`
  ).toString(); // Tambahkan .toString() di sini

  // Simpan data terenkripsi di cookie
  Cookies.set(param, cookiesEncrypt, options);
}

export function checkAuthorization(page: any) {
  const roleId = getCookiesDecrypt("urie");
  const levelNumber = getCookiesDecrypt("ulne");
  if (
    (Number(roleId) !== 3 &&
      Number(roleId) !== 4 &&
      Number(roleId) !== 11 &&
      Number(roleId) !== 12 &&
      Number(roleId) !== 2) ||
    roleId == undefined
  ) {
    console.log("Wrong Authentication");
    // window.location.href = "/";
  } else if (page == "admin" && Number(levelNumber) !== 1) {
    console.log("Wrong Authentication Admin");
    // window.location.href = "/";
  }
}

export function checkLoginSession() {
  const userId = getCookiesDecrypt("uie");
  const jwt = Cookies.get("access_token");
  const data = {
    userId,
    jwt,
  };
  // doCheckSession(data);
}
