"use client"; // components/Header.jsx
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Icon } from "@iconify/react";
import Image from "next/image";
import { useRouter } from "next/router";
import "bootstrap-icons/font/bootstrap-icons.css";
import SettingsModal from "@/components/header/settingsModal/SettingsModal";
import { RootState } from "@/redux/store";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";

import { getSystemSettingsThunk } from "@/redux/thunks/getSystemSettingsThunk";

function Header() {
  const router = useRouter();
  const [showSettingsModal, setShowSettingsModal] = useState(false);
  const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false);
  const autoLogoutTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  // Removed duplicate declaration of deviceName

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

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

  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]);

  // Auto-Logout nach 1 Minute (Test): nutzt adminLoginTime aus localStorage
  useEffect(() => {
    // Timer bereinigen, wenn sich der Status ändert
    if (autoLogoutTimerRef.current) {
      clearTimeout(autoLogoutTimerRef.current);
      autoLogoutTimerRef.current = null;
    }

    if (!isAdminLoggedIn) return;

    const iso = localStorage.getItem("adminLoginTime");
    const loginTime = iso ? new Date(iso).getTime() : Date.now();
    if (!iso) {
      // Falls älterer Login ohne Zeitstempel, setze jetzt
      try {
        localStorage.setItem(
          "adminLoginTime",
          new Date(loginTime).toISOString()
        );
      } catch {
        void 0; // ignore write errors (e.g., storage disabled)
      }
    }

    // 1 Minute ab Login (60_000 ms), eine Stunde (3_600_000 ms) im Produktivbetrieb
    const target = loginTime + 3_600_000;
    const delay = Math.max(0, target - Date.now());

    // Fallback: wenn Datum in Vergangenheit (z.B. Uhrzeit geändert), sofort abmelden
    autoLogoutTimerRef.current = setTimeout(() => {
      // Versuche den Button zu klicken, falls vorhanden
      const btn = document.querySelector<HTMLButtonElement>(
        'button[aria-label="Abmelden"]'
      );
      if (btn) {
        btn.click();
      } else {
        // Fallback direkt
        handleLogout();
      }
    }, delay);

    return () => {
      if (autoLogoutTimerRef.current) {
        clearTimeout(autoLogoutTimerRef.current);
        autoLogoutTimerRef.current = null;
      }
    };
  }, [isAdminLoggedIn, handleLogout]);
  //----------------------------------------------------------------
  const dispatch = useDispatch<AppDispatch>();

  const deviceName = useSelector(
    (state: RootState) => state.systemSettingsSlice.deviceName
  );

  useEffect(() => {
    if (!deviceName) {
      dispatch(getSystemSettingsThunk());
    }
  }, [deviceName, dispatch]);
  //----------------------------------------------------------------

  // Dark/Light Mode Toggle (persisted)
  const [isDark, setIsDark] = useState(false);
  // Initial state from html class / localStorage (set by _document script before hydration)
  useEffect(() => {
    if (typeof window === "undefined") return;
    const html = document.documentElement;
    const stored = localStorage.getItem("theme");
    const active = stored ? stored === "dark" : html.classList.contains("dark");
    setIsDark(active);
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const html = document.documentElement;
    if (isDark) {
      html.classList.add("dark");
      localStorage.setItem("theme", "dark");
    } else {
      html.classList.remove("dark");
      localStorage.setItem("theme", "light");
    }
  }, [isDark]);

  // Keyboard shortcut Alt + D to toggle theme
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.altKey && (e.key === "d" || e.key === "D")) {
        e.preventDefault();
        setIsDark((d) => !d);
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []);

  return (
  <header className="bg-[var(--color-surface)] dark:bg-[var(--color-surface)]/90 backdrop-blur flex justify-between items-center w-full h-[13vh] laptop:h-[10vh] relative text-[var(--color-fg)] dark:text-[var(--color-fg)] shadow-sm border-b border-[var(--color-border)]">
      <div
        className="absolute transform -translate-y-1/2 
                left-[8%] sm:left-[8%] md:left-[8%] lg:left-[8%] xl:left-[6%] 2xl:left-[2%] laptop:left-[4%] laptop:
                top-[90%] sm:top-[90%] md:top-[90%] lg:top-[90%] xl:top-[90%]"
        style={{
          height: "10vh", // 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>
      {/* TALAS-Logo + Text nebeneinander (flexibel oben links) */}
      <div className="flex items-center space-x-8 transform translate-x-3/4 mt-8 laptop:ml-10 laptop:translate-y-1 laptop:mt-4">
        <Image
          src="/images/logo-talas-2024.png"
          alt="TALAS Logo"
          className="object-contain w-[120px] laptop:w-[80px] xl:w-[140px] 2xl:w-[180px]"
          width={160}
          height={60}
          priority
        />
        <div className="flex flex-col leading-tight whitespace-nowrap">
          <h2 className="text-xl laptop:text-base xl:text-lg font-bold text-[var(--color-fg)]">
            Meldestation
          </h2>
          <p className="text-[var(--color-fg-muted)] text-lg laptop:text-sm xl:text-base truncate max-w-[20vw]">
            {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 gap-4">
          {/* Dark/Light Mode Toggle */}
          <button
            aria-label={isDark ? "Light Mode" : "Dark Mode"}
            onClick={() => setIsDark((d) => !d)}
            className="rounded-full p-2 bg-[var(--color-surface-alt)]/80 hover:bg-[var(--color-surface-alt)] dark:bg-[var(--color-surface-alt)]/60 dark:hover:bg-[var(--color-surface-alt)] transition border border-[var(--color-border)]"
            title={isDark ? "Light Mode" : "Dark Mode"}
          >
            {isDark ? (
              <Icon icon="mdi:weather-night" className="text-xl text-yellow-300" />
            ) : (
              <Icon icon="mdi:white-balance-sunny" className="text-xl text-yellow-500" />
            )}
          </button>
        </div>

        {/* Logout-Button - nur anzeigen wenn Admin eingeloggt ist */}
        {isAdminLoggedIn && (
          <div className="flex items-center justify-end w-1/4 space-x-1">
            <button
              onClick={handleLogout}
              aria-label="Abmelden"
              className="px-4 py-2 rounded bg-[var(--color-accent)] text-white hover:brightness-110 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-ring)] focus:ring-offset-2 focus:ring-offset-[var(--color-background)] transition"
            >
              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-[var(--color-warning)] text-center py-2 text-black font-bold tracking-wide">
          Admin-Modus aktiv
        </div>
      )}

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

export default Header;
