"use client"; // components/Header.jsx
import React, { useState, useEffect } from "react";
import Image from "next/image";
import { useRouter } from "next/router";
import "bootstrap-icons/font/bootstrap-icons.css";
import SettingsModal from "./modales/settingsModal/SettingsModal";
import { useSelector } from "react-redux";
import decodeToken from "../utils/decodeToken";

function Header() {
  const router = useRouter();
  const [showSettingsModal, setShowSettingsModal] = useState(false);
  const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false);
  const deviceName = useSelector((state) => state.variables.deviceName);

  const handleSettingsClick = () => setShowSettingsModal(true);
  const handleCloseSettingsModal = () => setShowSettingsModal(false);

  const handleLogout = () => {
    sessionStorage.removeItem("token"); // Token entfernen
    localStorage.setItem("isAdminLoggedIn", "false"); // Admin-Status entfernen
    setIsAdminLoggedIn(false); // Zustand sofort aktualisieren
    router.push("/offline.html"); // Weiterleitung
  };

  const handleLogin = () => {
    const token = JSON.stringify({ exp: Date.now() + 5 * 60 * 1000 }); // Beispiel-Token mit 5 Minuten Ablaufzeit
    sessionStorage.setItem("token", token); // Token speichern
    localStorage.setItem("isAdminLoggedIn", "true"); // Admin-Status setzen
    setIsAdminLoggedIn(true); // Zustand sofort aktualisieren
  };

  useEffect(() => {
    // Initialer Check beim Laden der Komponente
    const isAdmin = localStorage.getItem("isAdminLoggedIn") === "true";
    setIsAdminLoggedIn(isAdmin);

    // Beobachten von Änderungen in localStorage
    const interval = setInterval(() => {
      const updatedIsAdmin = localStorage.getItem("isAdminLoggedIn") === "true";
      if (updatedIsAdmin !== isAdminLoggedIn) {
        setIsAdminLoggedIn(updatedIsAdmin);
      }
    }, 500); // Überprüfung alle 500ms

    return () => {
      clearInterval(interval); // Intervall stoppen, wenn die Komponente entladen wird
    };
  }, [isAdminLoggedIn]);

  return (
    <header className="bg-gray-300 flex justify-between items-center w-full h-28 relative text-black">
      <div className="absolute left-32 top-32 transform -translate-y-1/2">
        <Image
          src="/images/Logo.png"
          alt="Logo"
          width={80}
          height={80}
          style={{ width: "auto", height: "auto" }}
          priority={false}
        />
      </div>
      <div className="w-64 flex-shrink-0 h-full mt-24 "></div>

      <div className="flex items-start space-x-4 w-full">
        <div className="flex flex-col text-left pl-8">
          <h2 className="text-base">Stationsname</h2>
          <p className="text-base text-gray-600">{deviceName}</p>
        </div>
      </div>

      <div className="p-4 w-full lg:w-full flex flex-row gap-4 justify-between">
        <div className="flex items-center justify-end w-full">
          <button
            onClick={handleSettingsClick}
            className="text-3xl text-black mr-7"
          >
            <i className="bi bi-gear"></i>
          </button>
        </div>
        <div className="flex items-center justify-end w-full space-x-2">
          <button
            onClick={handleLogout}
            className="bg-littwin-blue text-white px-4 py-2 rounded"
          >
            Abmelden
          </button>
        </div>
      </div>

      {/* Warnhinweis, wenn der Admin angemeldet ist */}
      {isAdminLoggedIn && (
        <div className="absolute top-0 left-0 w-full h-8 bg-yellow-400 text-center py-2 text-black font-bold">
          Admin-Modus aktiv
        </div>
      )}

      {showSettingsModal && (
        <SettingsModal
          showModal={showSettingsModal}
          onClose={handleCloseSettingsModal}
        />
      )}
    </header>
  );
}

export default Header;
