"use client"; // components/modales/KueModal.jsx
import ReactModal from "react-modal";
import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import type { RootState } from "../../../../redux/store";
import "bootstrap-icons/font/bootstrap-icons.css";
import handleSave, { OriginalValues } from "./handlers/handleSave";
import handleDisplayEinschalten from "./handlers/handleDisplayEinschalten";
import firmwareUpdate from "./handlers/firmwareUpdate";
import decodeToken from "../../../../utils/decodeToken";
import { setKueData } from "../../../../redux/slices/kueDataSlice";

interface KueModalProps {
  showModal: boolean;
  onClose: () => void;
  slot: number;
  onModulNameChange: (id: string) => void;
}

function KueModal({
  showModal,
  onClose,
  slot,
  onModulNameChange,
}: KueModalProps): JSX.Element {
  const dispatch = useDispatch();
  const isAdminLoggedIn = useSelector(
    (state: any) => state.authSlice.isAdminLoggedIn
  );
  const [isAdmin, setIsAdmin] = useState(false);

  const {
    kueID,
    kueLimit1,
    kueDelay1,
    kueLimit2Low,
    kueLimit2High,
    kueLoopInterval,
  } = useSelector((state: RootState) => state.kueDataSlice);

  const [bezeichnungen, setBezeichnungen] = useState(Array(32).fill(""));

  const [originalValues, setOriginalValues] = useState<OriginalValues>({
    kueID: Array(32).fill(""),
    kueBezeichnungen: Array(32).fill(""),
    isolationsgrenzwerte: Array(32).fill(10.0),
    verzoegerung: Array(32).fill(1.0),
    untereSchleifenGrenzwerte: Array(32).fill(0.1),
    obereSchleifenGrenzwerte: Array(32).fill(1.0),
    schleifenintervall: Array(32).fill(24),
  });

  useEffect(() => {
    if (showModal) {
      setBezeichnungen(
        kueID
          ? kueID.map((name: string) => name.trim() || "---")
          : bezeichnungen
      );

      setOriginalValues({
        kueID: [...kueID],
        kueBezeichnungen: [...bezeichnungen],
        isolationsgrenzwerte: [...kueLimit1],
        verzoegerung: [...kueDelay1],
        untereSchleifenGrenzwerte: [...kueLimit2Low],
        obereSchleifenGrenzwerte: [...kueLimit2High],
        schleifenintervall: [...kueLoopInterval],
      });
    }
  }, [
    showModal,
    kueID,
    kueLimit1,
    kueDelay1,
    kueLimit2Low,
    kueLimit2High,
    kueLoopInterval,
  ]);

  useEffect(() => {
    const token = sessionStorage.getItem("token");
    if (token) {
      const decoded = decodeToken(token);
      setIsAdmin(decoded?.role?.toLowerCase() === "admin");
    }
  }, [showModal]);

  const handleSaveWrapper = () => {
    handleSave({
      ids: [...kueID],
      bezeichnungen,
      isolationsgrenzwerte: [...kueLimit1],
      verzoegerung: [...kueDelay1],
      untereSchleifenGrenzwerte: [...kueLimit2Low],
      obereSchleifenGrenzwerte: [...kueLimit2High],
      schleifenintervall: [...kueLoopInterval],
      originalValues,
      slot,
      dispatch,
      onModulNameChange,
      onClose,
    });
  };

  // Korrekte updateArray Methode ohne Thunk
  const updateArray = (
    key: keyof RootState["kueDataSlice"],
    array: number[],
    value: number
  ) => {
    const updatedArray = [...array];
    updatedArray[slot] = value;
    dispatch(setKueData({ [key]: updatedArray }));
  };

  const handleDisplayEinschaltenWrapper = () => {
    handleDisplayEinschalten(slot);
  };

  return (
    <ReactModal
      isOpen={showModal}
      onRequestClose={onClose}
      ariaHideApp={false}
      style={{
        overlay: {
          backgroundColor: "rgba(0, 0, 0, 0.5)",
          zIndex: 100,
        },
        content: {
          top: "50%",
          left: "50%",
          right: "auto",
          bottom: "auto",
          transform: "translate(-50%, -50%)",
          width: "90%",
          maxWidth: "800px",
          padding: "10px",
          borderRadius: "8px",
          border: "none",
        },
      }}
    >
      <div className="flex items-center justify-between bg-littwin-blue text-white p-1 rounded-t-lg">
        <h2 className="text-sm font-bold">KUE Einstellung - Slot {slot + 1}</h2>
        <button
          onClick={onClose}
          className="absolute top-2 right-4 text-white text-xl"
        >
          <i className="bi bi-x-circle-fill"></i>
        </button>
      </div>

      <div className="p-2 mb-4 text-black">
        <label className="font-bold">Kabelbezeichnung:</label>
        <input
          type="text"
          className="border rounded p-1 w-full text-sm"
          value={kueID[slot] || ""}
          onChange={(e) => {
            const newIds = [...kueID];
            newIds[slot] = e.target.value;
            dispatch(setKueData({ kueID: newIds }));
          }}
        />
      </div>

      <div className="p-2 text-black">
        <h3 className="font-bold text-center mb-4">Isolationsmessung</h3>
        <table className="w-full text-left border-collapse mb-4">
          <thead className="bg-gray-100">
            <tr>
              <th className="p-2 border text-sm text-center">
                Grenzwert (MOhm)
              </th>
              <th className="p-2 border text-sm text-center">
                Verzögerung (sek)
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td className="p-2 border text-center">
                <input
                  type="number"
                  step="0.1"
                  className="w-[6rem] border rounded p-1 text-sm"
                  value={kueLimit1[slot] ?? ""}
                  onChange={(e) =>
                    updateArray(
                      "kueLimit1",
                      kueLimit1,
                      parseFloat(e.target.value)
                    )
                  }
                />
              </td>
              <td className="p-2 border text-center">
                <input
                  type="number"
                  step="0.1"
                  className="w-[6rem] border rounded p-1 text-sm"
                  value={kueDelay1[slot] ?? ""}
                  onChange={(e) =>
                    updateArray(
                      "kueDelay1",
                      kueDelay1,
                      parseFloat(e.target.value)
                    )
                  }
                />
              </td>
            </tr>
          </tbody>
        </table>

        <h3 className="font-bold text-center mb-4">Schleifenmessung</h3>
        <table className="w-full text-left border-collapse">
          <thead className="bg-gray-100">
            <tr>
              <th className="p-2 border text-sm text-center">
                Grenzwert (kOhm)
              </th>
              <th className="p-2 border text-sm text-center">
                Schleifenintervall (h)
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td className="p-2 border text-center">
                <input
                  type="number"
                  step="0.1"
                  className="w-[6rem] border rounded p-1 text-sm"
                  value={kueLimit2Low[slot] ?? ""}
                  onChange={(e) =>
                    updateArray(
                      "kueLimit2Low",
                      kueLimit2Low,
                      parseFloat(e.target.value)
                    )
                  }
                />
              </td>
              <td className="p-2 border text-center">
                <input
                  type="number"
                  step="0.1"
                  className="w-[6rem] border rounded p-1 text-sm"
                  value={kueLoopInterval[slot] ?? ""}
                  onChange={(e) =>
                    updateArray(
                      "kueLoopInterval",
                      kueLoopInterval,
                      parseFloat(e.target.value)
                    )
                  }
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div className="flex justify-end bg-gray-100 p-4 rounded-b-lg">
        {isAdminLoggedIn && (
          <button
            onClick={() => firmwareUpdate(slot)}
            className="bg-littwin-blue text-white p-2 rounded flex items-center mr-2"
          >
            Firmware Update
          </button>
        )}
        <button
          onClick={handleDisplayEinschaltenWrapper}
          className="bg-littwin-blue text-white p-2 rounded flex items-center mr-2"
        >
          <span className="mr-2">📺</span> Display einschalten
        </button>
        <button
          onClick={handleSaveWrapper}
          className="bg-littwin-blue text-white p-2 rounded flex items-center"
        >
          <span className="mr-2">💾</span> Speichern
        </button>
      </div>
    </ReactModal>
  );
}

export default KueModal;
