// components/header/settingsModal/hooks/useAdminAuth.ts
import { useState, useEffect } from "react";
import CryptoJS from "crypto-js";

function decryptToken(encryptedToken: string) {
  const encryptionKey = process.env.NEXT_PUBLIC_ENCRYPTION_KEY;
  const encryptionIV = process.env.NEXT_PUBLIC_ENCRYPTION_IV;

  if (!encryptionKey || !encryptionIV) {
    throw new Error("Encryption key or IV is not defined.");
  }

  const key = CryptoJS.enc.Utf8.parse(encryptionKey);
  const iv = CryptoJS.enc.Utf8.parse(encryptionIV);

  const bytes = CryptoJS.AES.decrypt(encryptedToken, key, { iv });
  return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}

export function useAdminAuth(showModal: boolean) {
  const [isAdminLoggedIn, setAdminLoggedIn] = useState(false);

  function logoutAdmin() {
    sessionStorage.removeItem("token");
    localStorage.setItem("isAdminLoggedIn", "false");
    setAdminLoggedIn(false);
  }

  useEffect(() => {
    if (showModal) {
      const token = sessionStorage.getItem("token");
      if (token) {
        try {
          const { exp } = decryptToken(token);
          if (Date.now() < exp) {
            setAdminLoggedIn(true);
          } else {
            logoutAdmin();
          }
        } catch (error) {
          console.error("Token-Entschlüsselung fehlgeschlagen:", error);
          logoutAdmin();
        }
      }
    }
  }, [showModal]);

  return { isAdminLoggedIn, logoutAdmin };
}
