// components/Header.jsx
"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import "bootstrap-icons/font/bootstrap-icons.css";
import { loadWindowVariables } from "../utils/loadWindowVariables"; // Importiere die Funktion
import SettingsModal from "./modales/SettingsModal";

function Header() {
  const [isClient, setIsClient] = useState(false);
  const [stationsname, setStationsname] = useState("Lädt..."); // Platzhalter
  const [cplStatus, setCplStatus] = useState("Lädt...");
  const [showSettingsModal, setShowSettingsModal] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const handleSettingsClick = () => {
    setShowSettingsModal(true); // Öffne das Modal
  };

  const handleCloseSettingsModal = () => {
    setShowSettingsModal(false); // Schließe das Modal
  };

  const handleLogout = () => {
    window.location.href = "/offline.html"; // Öffnet offline.html
  };

  useEffect(() => {
    if (typeof window !== "undefined") {
      console.log("Lade Window-Variablen...");

      loadWindowVariables()
        .then(() => {
          if (window.ip) {
            setStationsname(window.deviceName || "Unbekannt");
            setCplStatus(window.hardware_version || "Unbekannt");
          } else {
            console.error("window.ip ist nicht verfügbar.");
          }
        })
        .catch((error) => {
          console.error("Fehler beim Laden der Variablen:", error);
        });
    }
  }, [isClient]);
  useEffect(() => {
    if (typeof window !== "undefined") {
      console.log("Systemvariablen geladen:", {
        // last20Messages.acp
        last20Messages: window.last20Messages,
        // System.acp Variablen
        deviceName: window.deviceName,
        mac1: window.mac1,
        mac2: window.mac2,
        ip: window.ip,
        subnet: window.subnet,
        gateway: window.gateway,
        datetime: window.datetime,
        // de.acp Variablen
        de: window.de,
        counter: window.counter,
        flutter: window.flutter,
        // kueConfig.acp Variablen
        kueOnline: window.kueOnline,
        kueID: window.kueID,
        //kueIso: window.kueIso, von SERVICE/kueConfig.acp also von window.kueIso
        // kuedetail.acp Variablen
        kueValid: window.kueValid,
        kueAlarm1: window.kueAlarm1,
        kueAlarm2: window.kueAlarm2,
        kueRes: window.kueRes,
        kueCableBreak: window.kueCableBreak,
        kueGroundFault: window.kueGroundFault,
        kueLimit1: window.kueLimit1,
        kueLimit2Low: window.kueLimit2Low,
        kueLimit2High: window.kueLimit2High,
        kueDelay1: window.kueDelay1,
        kueLoopInterval: window.kueLoopInterval,
        kueVersion: window.kueVersion,
        tdrAtten: window.tdrAtten,
        tdrPulse: window.tdrPulse,
        tdrSpeed: window.tdrSpeed,
        tdrAmp: window.tdrAmp,
        tdrTrigger: window.tdrTrigger,
        tdrLocation: window.tdrLocation,
        tdrActive: window.tdrActive,
        kueOverflow: window.kueOverflow,
        kue100V: window.kue100V,
        kueResidence: window.kueResidence,
        tdrLastMeasurement: window.tdrLastMeasurement,
        kueBooting: window.kueBooting,
        appVersion: window.appVersion,
      });
    }
  }, []);

  useEffect(() => {
    if (isClient) {
      const files = [
        "de.acp",
        "kueConfig.acp",
        "kueData.js",
        "kueDetailTdr.acp",
        "Start.acp",
        "System.acp",
      ];

      const environment = process.env.NEXT_PUBLIC_NODE_ENV || "production"; // Fallback auf 'production'

      files.forEach((file) => {
        const script = document.createElement("script");

        if (environment === "production") {
          script.src = `/CPL?/CPL/SERVICE/${file}`; // Produktions-Pfad
        } else {
          script.src = `/mockData/${file}`; // Entwicklungs-Pfad
        }

        script.async = true;
        script.onload = () => console.log(`${file} wurde erfolgreich geladen.`);
        script.onerror = (error) =>
          console.error(`Fehler beim Laden von ${file}:`, error);
        document.head.appendChild(script);
      });
    }
  }, [isClient]);

  useEffect(() => {
    console.log("Environment:", process.env.NEXT_PUBLIC_NODE_ENV); // Logge die Umgebungsvariable
  }, []);

  if (!isClient) return null; // Rendere die Komponente nicht, bis sie clientseitig ausgeführt wird

  return (
    <header className="bg-gray-300 flex justify-between items-center w-full h-28 relative">
      <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>

      {/* CPL Status und Stationsname */}
      <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">{stationsname}</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">
          <button
            onClick={handleLogout}
            className="text bg-littwin-blue text-white px-4 py-2 rounded"
          >
            Abmelden
          </button>
        </div>
      </div>
      {showSettingsModal && (
        <SettingsModal
          showModal={showSettingsModal}
          onClose={handleCloseSettingsModal}
        />
      )}
    </header>
  );
}

export default Header;
