"use client";
import React, { useState, useEffect } from "react";
import { RootState } from "../../../redux/store";
import { useSelector } from "react-redux";

import handleReboot from "./handlers/handleReboot";
import handleSetDateTime from "./handlers/handleSetDateTime";
// import { useAdminAuth } from "./hooks/useAdminAuth";
// import handleAdminLogin from "./handlers/handleAdminLogin";
import { useDispatch } from "react-redux";
import { AppDispatch } from "../../../redux/store";
import { getSystemSettingsThunk } from "../../../redux/thunks/getSystemSettingsThunk";
import handleGeneralSubmit from "./handlers/handleGeneralSubmit";
import handleKueFirmwareUpdate from "@/components/main/settingsPageComponents/handlers/handleKueFirmwareUpdate";
import { useAdminAuth } from "@/components/main/settingsPageComponents/hooks/useAdminAuth";
import ProgressModal from "@/components/main/settingsPageComponents/modals/ProgressModal";

import "react-toastify/dist/ReactToastify.css";

const GeneralSettings: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const systemSettings = useSelector(
    (state: RootState) => state.systemSettingsSlice
  );
  const [isUpdating, setIsUpdating] = useState(false);
  const [progress, setProgress] = useState(0);

  const { isAdminLoggedIn } = useAdminAuth(true);

  // const [error, setError] = useState("");

  const [name, setName] = useState(systemSettings.deviceName || "");
  const [mac1, setMac1] = useState(systemSettings.mac1 || "");
  const [ip, setIp] = useState(systemSettings.ip || "");
  const [subnet, setSubnet] = useState(systemSettings.subnet || "");
  const [gateway, setGateway] = useState(systemSettings.gateway || "");
  const [systemUhr, setSystemUhr] = useState(
    systemSettings.cplInternalTimestamp || ""
  );

  // Add loginSuccess state if you want to use it for feedback
  // const [loginSuccess, setLoginSuccess] = useState(false);

  useEffect(() => {
    if (!systemSettings.deviceName) {
      dispatch(getSystemSettingsThunk());
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  /*
  fix: Initialwerte in Allgemeine Einstellungen bei Seitenaufruf setzen

- useEffect hinzugefügt, um lokale States mit Redux-Daten zu synchronisieren
- Problem behoben, dass Felder beim ersten Laden leer waren

  */
  useEffect(() => {
    setName(systemSettings.deviceName || "");
    setIp(systemSettings.ip || "");
    setSubnet(systemSettings.subnet || "");
    setGateway(systemSettings.gateway || "");
    setSystemUhr(systemSettings.cplInternalTimestamp || "");
    setMac1(systemSettings.mac1 || "");
  }, [systemSettings]);

  return (
    <div className="p-6 md:p-3 bg-gray-100 dark:bg-gray-800 max-w-5xl mr-auto overflow-y-auto max-h-[calc(100vh-200px)] text-gray-900 dark:text-gray-100 ">
      <h2 className="text-sm md:text-md font-bold mb-2">
        Allgemeine Einstellungen
      </h2>
      <form className="grid grid-cols-1 md:grid-cols-2 gap-2">
        {/* Geräte-Name */}
        <div className="col-span-2">
          <label className="block text-xs md:text-sm font-medium">Name:</label>
          <input
            type="text"
            className="border border-gray-300 dark:border-gray-700 rounded h-8 p-1 w-full text-xs bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>

        {/* MAC Adresse */}
        <div>
          <label className="block text-xs md:text-sm font-medium">
            MAC Adresse 1:
          </label>
          <input
            type="text"
            className="border border-gray-300 dark:border-gray-700 rounded h-8 p-1 w-full text-xs bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
            value={mac1}
            disabled
          />
        </div>

        {/* Systemzeit */}
        <div className="col-span-2">
          <label className="block text-xs md:text-sm font-medium mb-1">
            Systemzeit:
          </label>
          <div className="flex flex-row gap-2">
            <input
              type="text"
              className="border border-gray-300 dark:border-gray-700 rounded h-8 p-1 w-full text-xs bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
              value={systemUhr.replace(/\s*Uhr$/, "")}
              disabled
            />
            <button
              type="button"
              className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
              onClick={() => handleSetDateTime()}
            >
              Systemzeit übernehmen
            </button>
          </div>
        </div>

        {/* Netzwerk */}
        <div>
          <label className="block text-xs md:text-sm font-medium">IP:</label>
          <input
            type="text"
            className="border border-gray-300 dark:border-gray-700 rounded h-8 p-1 w-full text-xs bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
            value={ip}
            onChange={(e) => setIp(e.target.value)}
          />
        </div>
        <div>
          <label className="block text-xs md:text-sm font-medium">
            Subnet:
          </label>
          <input
            type="text"
            className="border border-gray-300 dark:border-gray-700 rounded h-8 p-1 w-full text-xs bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
            value={subnet}
            onChange={(e) => setSubnet(e.target.value)}
          />
        </div>
        <div>
          <label className="block text-xs md:text-sm font-medium">
            Gateway:
          </label>
          <input
            type="text"
            className="border border-gray-300 dark:border-gray-700 rounded h-8 p-1 w-full text-xs bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
            value={gateway}
            onChange={(e) => setGateway(e.target.value)}
          />
        </div>

        {/* Buttons */}
        <div className="col-span-2 flex flex-wrap md:justify-between gap-1 mt-2">
          <button
            type="button"
            className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
            onClick={() => handleReboot()}
          >
            Neustart CPL
          </button>
          {isAdminLoggedIn && (
            <button
              type="button"
              className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
              onClick={() => {
                const confirmed = window.confirm(
                  "⚠️ Wollen Sie wirklich ein Firmwareupdate für alle KÜ-Module starten?"
                );
                if (confirmed) {
                  setIsUpdating(true);
                  setProgress(0);

                  const updateDuration = 300; // Sekunden (5 Minuten)
                  const intervalMs = 1000;
                  let elapsed = 0;

                  const interval = setInterval(() => {
                    elapsed++;
                    const newProgress = Math.min(
                      (elapsed / updateDuration) * 100,
                      100
                    );
                    setProgress(newProgress);
                    if (elapsed >= updateDuration) {
                      clearInterval(interval);
                      setIsUpdating(false);
                    }
                  }, intervalMs);

                  handleKueFirmwareUpdate()
                    .then(() => {
                      clearInterval(interval);
                      setProgress(100);

                      setTimeout(() => {
                        setIsUpdating(false);
                        setProgress(100);

                        setTimeout(() => {
                          alert("✅ Firmwareupdate erfolgreich abgeschlossen.");
                        }, 300); // Nach Modal-Schließung
                      }, 500);
                    })
                    .catch((error) => {
                      console.error("Update-Fehler:", error);
                      clearInterval(interval);
                      setIsUpdating(false);
                    });
                }
              }}
            >
              Firmwareupdate alle KÜ-Module
            </button>
          )}

          <ProgressModal visible={isUpdating} progress={progress} />

          <button
            type="button"
            className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
            onClick={() =>
              handleGeneralSubmit(
                {
                  name: systemSettings.deviceName ?? "",
                  ip: systemSettings.ip ?? "",
                  subnet: systemSettings.subnet ?? "",
                  gateway: systemSettings.gateway ?? "",
                },
                {
                  name,
                  ip,
                  subnet,
                  gateway,
                }
              )
            }
          >
            Speichern
          </button>
        </div>
      </form>
    </div>
  );
};

export default GeneralSettings;
