"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-[12vh] sm:h-[11vh] md:h-[12vh] lg:h-[13vh] xl:h-[12vh] relative text-black mb-16 sm:mb-1 md:mb-1 lg:mb-1 xl:mb-1 2xl:mb-12">
      <div
        className="absolute transform -translate-y-1/2 
                left-[8%] sm:left-[8%] md:left-[8%] lg:left-[8%] xl:left-[6%]
                top-[90%] sm:top-[90%] md:top-[90%] lg:top-[90%] xl:top-[90%]"
        style={{
          height: "13vh", // Dynamische Höhe des Containers
          width: "auto",
          aspectRatio: "1", // Beibehaltung des Seitenverhältnisses
        }}
      >
        <Image
          src="/images/Logo.png"
          alt="Logo"
          fill
          sizes="(max-width: 640px) 7vh, (max-width: 1024px) 8vh, (max-width: 1280px) 9vh, 10vh"
          className="object-contain"
          priority={false}
        />
      </div>
      {/* Stationsname & Device Name */}
      <div
        className="absolute transform -translate-y-1/2
                left-[23%] sm:left-[20%] md:left-[21%] lg:left-[22%] xl:left-[23%]
                top-[50%] flex flex-col justify-center space-y-1"
      >
        <h2 className="text-lg sm:text-sm md:text-base lg:text-lg xl:text-xl font-bold">
          Stationsname
        </h2>
        <p className="text-gray-600 text-base sm:text-sm md:text-base lg:text-lg xl:text-xl">
          {deviceName}
        </p>
      </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-0"
          >
            <i className="bi bi-gear"></i>
          </button>
        </div>
        <div className="flex items-center justify-end w-1/4 space-x-1">
          <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-1/2 transform -translate-x-1/2 w-full xl:w-1/4 2xl:w-1/4 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;
