"use client";
import React, { useState, useEffect } from "react";
import { RootState } from "../../../redux/store";
import { useSelector } from "react-redux";
import handleClearDatabase from "./handlers/dbHandlers/handleClearDatabase";
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 { fetchSystemSettingsThunk } from "../../../redux/thunks/fetchSystemSettingsThunk";
import handleGeneralSubmit from "./handlers/handleGeneralSubmit";

const GeneralSettings: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const systemSettings = useSelector(
    (state: RootState) => state.systemSettingsSlice
  );

  const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(true);
  const [loginSuccess, setLoginSuccess] = useState(false);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  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 || ""
  );

  const handleLogin = async () => {
    handleAdminLogin(
      username,
      password,
      () => {
        setLoginSuccess(true);
        setError("");
      },
      (errorMsg) => {
        setLoginSuccess(false);
        setError(errorMsg);
      },
      dispatch
    );
  };

  useEffect(() => {
    if (!systemSettings.deviceName) {
      dispatch(fetchSystemSettingsThunk());
    }
  }, []);
  /*
  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 max-w-5xl mr-auto overflow-y-auto max-h-[calc(100vh-200px)] ">
      <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 rounded h-8 p-1 w-full text-xs"
            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 rounded h-8 p-1 w-full text-xs"
            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 rounded h-8 p-1 w-full text-xs"
              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 rounded h-8 p-1 w-full text-xs"
            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 rounded h-8 p-1 w-full text-xs"
            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 rounded h-8 p-1 w-full text-xs"
            value={gateway}
            onChange={(e) => setGateway(e.target.value)}
          />
        </div>

        {/* Admin Login */}
        {/*
                        <div className="col-span-2 flex flex-col gap-1">
          {isAdminLoggedIn ? (
            <button
              type="button"
              className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
              onClick={logoutAdmin}
            >
              Admin abmelden
            </button>
          ) : (
            <>
              <div className="flex flex-row gap-3">
                <input
                  type="text"
                  placeholder="Benutzername"
                  className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                />
                <input
                  type="password"
                  placeholder="Passwort"
                  className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <button
                  type="button"
                  className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
                  onClick={handleLogin}
                >
                  Admin anmelden
                </button>
              </div>
            </>
          )}
        </div>
                */}

        {/* Feedback */}
        {loginSuccess && (
          <p className="text-green-600 text-xs">Login erfolgreich!</p>
        )}
        {error && <p className="text-red-500 text-xs">{error}</p>}

        {/* 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>

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