"use client"; // components/header/settingsModal/SettingsModal.tsx
import React, { useState, useEffect } from "react";
import ReactModal from "react-modal";
import "bootstrap-icons/font/bootstrap-icons.css";
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 bcrypt from "bcryptjs";
import CryptoJS from "crypto-js";
import { useAdminAuth } from "./hooks/useAdminAuth";
import { useSystemSettings } from "./hooks/useSystemSettings";
import { generateKeyAndIV, generateToken } from "./utils/cryptoUtils";
import USERS from "./config/users";
import handleAdminLogin from "./handlers/handleAdminLogin";

ReactModal.setAppElement("#__next");

function SettingModal({ showModal, onClose }) {
  const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(showModal);

  const { formValues, setFormValues } = useSystemSettings(showModal);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [showLoginForm, setShowLoginForm] = useState(false);

  const deviceName_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.deviceName
  );
  const mac1_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.mac1
  );
  const ip_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.ip
  );
  const subnet_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.subnet
  );
  const gateway_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.gateway
  );
  const datetime_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.cplInternalTimestamp
  );
  const ntp1_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.ntp1
  );
  const ntp2_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.ntp2
  );
  const ntp3_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.ntp3
  );
  const ntpTimezone_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.ntpTimezone
  );
  const active_Redux = useSelector(
    (state: RootState) => state.systemSettingsSlice.ntpActive
  );

  const [name, setName] = useState(deviceName_Redux || "");
  const [mac1, setMac1] = useState(mac1_Redux || "");
  const [ip, setIp] = useState(ip_Redux || "");
  const [subnet, setSubnet] = useState(subnet_Redux || "");
  const [gateway, setGateway] = useState(gateway_Redux || "");
  const [systemUhr, setSystemUhr] = useState(datetime_Redux || "");
  const [ntp1, setNtp1] = useState(ntp1_Redux || "");
  const [ntp2, setNtp2] = useState(ntp2_Redux || "");
  const [ntp3, setNtp3] = useState(ntp3_Redux || "");
  const [ntpTimezone, setNtpTimezone] = useState(ntpTimezone_Redux || "");
  const [active, setActive] = useState(active_Redux || "");

  const [originalValues, setOriginalValues] = useState({});
  const currentValues = {
    name,
    ip,
    subnet,
    gateway,
    ntp1,
    ntp2,
    ntp3,
    ntpTimezone,
    active,
  };

  return (
    <ReactModal
      isOpen={showModal}
      onRequestClose={onClose}
      shouldCloseOnOverlayClick={false}
      overlayClassName="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center"
      className="w-[90%] max-w-[800px] h-auto max-h-[85vh] lg:max-h-[75vh] xl:max-h-[85vh] 2xl:max-h-[90vh] 
             overflow-y-auto p-4 lg:p-2 xl:p-6 2xl:p-8 bg-white rounded-lg relative border-none 
             scale-90 lg:scale-75 xl:scale-90 2xl:scale-100"
    >
      <button
        onClick={onClose}
        className="absolute top-2 right-2 text-xl bg-transparent border-none cursor-pointer"
      >
        <i className="bi bi-x-circle-fill"></i>
      </button>

      <div className="text-black text-sm lg:text-xs xl:text-sm 2xl:text-base">
        <h2 className="text-lg font-bold mb-4">System:</h2>
        <form>
          {/* Name */}
          <div className="mb-2">
            <label className="block font-medium">Name:</label>
            <input
              type="text"
              className="border border-gray-300 rounded p-1 xl:p-2 w-full"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>

          {/* MAC Adresse und Systemuhr */}
          <div className="grid grid-cols-2 gap-2 lg:grid-cols-3 xl:grid-cols-4">
            <div>
              <label className="block font-medium">MAC Adresse 1:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={mac1}
                disabled
              />
            </div>
            <div>
              <label className="block font-medium">Systemuhr:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={systemUhr}
                disabled
              />
            </div>
            <div className="flex items-end">
              <button
                className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full"
                onClick={() => {
                  if (
                    window.confirm(
                      "Möchten Sie wirklich die Systemzeit übernehmen?"
                    )
                  ) {
                    handleSetDateTime();
                  }
                }}
              >
                Systemzeit übernehmen
              </button>
            </div>
          </div>

          {/* IP-Konfiguration */}
          <div className="grid grid-cols-2 gap-2 lg:grid-cols-3 xl:grid-cols-4">
            <div>
              <label className="block font-medium">IP:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={ip}
                onChange={(e) => setIp(e.target.value)}
              />
            </div>
            <div>
              <label className="block font-medium">Subnet:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={subnet}
                onChange={(e) => setSubnet(e.target.value)}
              />
            </div>
            <div>
              <label className="block font-medium">Gateway:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={gateway}
                onChange={(e) => setGateway(e.target.value)}
              />
            </div>
          </div>

          {/* SNTP Client */}
          <h3 className="text-sm font-bold my-2">SNTP Client:</h3>
          <div className="grid grid-cols-2 gap-2 lg:grid-cols-3 xl:grid-cols-4">
            <div>
              <label className="block font-medium">IP NTP Server 1:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={ntp1}
                onChange={(e) => setNtp1(e.target.value)}
              />
            </div>
            <div>
              <label className="block font-medium">IP NTP Server 2:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={ntp2}
                onChange={(e) => setNtp2(e.target.value)}
              />
            </div>
            <div>
              <label className="block font-medium">IP NTP Server 3:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={ntp3}
                onChange={(e) => setNtp3(e.target.value)}
              />
            </div>
            <div>
              <label className="block font-medium">Zeitzone:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={ntpTimezone}
                onChange={(e) => setNtpTimezone(e.target.value)}
              />
            </div>
            <div>
              <label className="block font-medium">NTP Active:</label>
              <input
                type="text"
                className="border border-gray-300 rounded p-1 xl:p-2 w-full"
                value={active}
                onChange={(e) => setActive(e.target.value)}
              />
            </div>
          </div>

          {/* Buttons: Skaliert für große Screens */}
          <div className="flex flex-col md:flex-row justify-between mt-4 gap-2">
            <button
              className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full md:w-auto"
              onClick={handleReboot}
            >
              Neustart CPL
            </button>
            <button
              onClick={() =>
                isAdminLoggedIn ? handleAdminLogout() : setShowLoginForm(true)
              }
              className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full md:w-auto"
            >
              {isAdminLoggedIn ? "Admin abmelden" : "Admin anmelden"}
            </button>
            <button
              className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full md:w-auto"
              onClick={handleClearDatabase}
            >
              Datenbank leeren
            </button>
            <button
              className="bg-littwin-blue text-white px-3 py-1 xl:px-4 xl:py-2 rounded w-full md:w-auto"
              onClick={() => handleSubmit(originalValues, currentValues)}
            >
              Übernehmen
            </button>
          </div>
        </form>
      </div>
    </ReactModal>
  );
}

export default SettingModal;
