"use client"; // /components/main/settingsPageComponents/GeneralSettings.tsx
import React, { useState } from "react";
import { RootState } from "../../../redux/store";
import { useSelector } from "react-redux";
import handleClearDatabase from "./handlers/handleClearDatabase";
import handleReboot from "./handlers/handleReboot";
import handleSetDateTime from "./handlers/handleSetDateTime";
import handleSubmit from "./handlers/handleSubmit";
import { useAdminAuth } from "./hooks/useAdminAuth";
import handleAdminLogin from "./handlers/handleAdminLogin";

const GeneralSettings = () => {
  const systemSettings = useSelector(
    (state: RootState) => state.systemSettings
  );

  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] = 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 [ntp1, setNtp1] = useState(systemSettings.ntp1 || "");
  const [ntp2, setNtp2] = useState(systemSettings.ntp2 || "");
  const [ntp3, setNtp3] = useState(systemSettings.ntp3 || "");
  const [ntpTimezone, setNtpTimezone] = useState(
    systemSettings.ntpTimezone || ""
  );
  const [active, setActive] = useState(systemSettings.ntpActive || false);
  const handleLogin = async () => {
    handleAdminLogin(
      username,
      password,
      () => {
        setLoginSuccess(true);
        setError("");
      },
      (errorMsg) => {
        setLoginSuccess(false);
        setError(errorMsg);
      }
    );
  };
  return (
    <div className="p-2 md:p-3 bg-gray-100 max-w-2xl mx-auto">
      <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 (nur Anzeige) */}
        <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 & Setzen */}
        <div className="flex flex-col md:flex-row md:items-center gap-1 col-span-2">
          <div className="flex-1">
            <label className="block text-xs md:text-sm font-medium">
              Systemzeit:
            </label>
            <input
              type="text"
              className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
              value={systemUhr}
              disabled
            />
          </div>
          <button
            type="button"
            className="bg-littwin-blue text-white px-2 py-1 rounded w-full md:w-auto text-xs"
            onClick={() => handleSetDateTime()}
          >
            Systemzeit übernehmen
          </button>
        </div>

        {/* ✅ Netzwerk-Einstellungen */}
        <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/Logout */}
        <div className="col-span-2 flex flex-col gap-1">
          {isAdminLoggedIn ? (
            <button
              type="button"
              className="bg-red-500 text-white px-2 py-1 rounded text-xs"
              onClick={logoutAdmin}
            >
              Admin abmelden
            </button>
          ) : (
            <>
              <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-2 py-1 rounded text-xs"
                onClick={handleLogin}
              >
                Admin anmelden
              </button>
            </>
          )}
        </div>

        {/* ✅ Feedback für den Benutzer */}
        {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-2 py-1 rounded text-xs w-full md:w-auto"
            onClick={() => handleReboot()}
          >
            Neustart CPL
          </button>
          <button
            type="button"
            className="bg-littwin-blue text-white px-2 py-1 rounded text-xs w-full md:w-auto"
            onClick={() => handleClearDatabase()}
          >
            Datenbank leeren
          </button>
          <button
            type="button"
            className="bg-littwin-blue text-white px-2 py-1 rounded text-xs w-full md:w-auto"
            onClick={() =>
              handleSubmit(
                {
                  name,
                  ip,
                  subnet,
                  gateway,
                  ntp1,
                  ntp2,
                  ntp3,
                  ntpTimezone,
                  active,
                },
                systemSettings
              )
            }
          >
            Speichern
          </button>
        </div>
      </form>
    </div>
  );
};

export default GeneralSettings;
