"use client";

declare global {
  interface Window {
    win_kueID?: string[];
    win_kueLimit1?: number[];
    win_kueDelay1?: number[];
    win_kueLimit2Low?: number[];
    win_kueLimit2High?: number[];
    win_kueLoopInterval?: number[];
    win_memoryInterval?: number[];
  }
}

import { useDispatch, useSelector } from "react-redux";
import type { RootState } from "../../../../../redux/store";
import { setKueData } from "../../../../../redux/slices/kueDataSlice";
import handleSave, { OriginalValues } from "../handlers/handleSave";
import handleDisplayEinschalten from "../handlers/handleDisplayEinschalten";
import firmwareUpdate from "../handlers/firmwareUpdate";
import { useAdminAuth } from "../../../settingsPageComponents/hooks/useAdminAuth";

interface Props {
  slot: number;
  onClose?: () => void;
  onModulNameChange?: (id: string) => void;
}

const memoryIntervalOptions = [
  { value: 0, label: "Kein" },
  { value: 1, label: "1 Minute" },
  { value: 5, label: "5 Minuten" },
  { value: 10, label: "10 Minuten" },
  { value: 15, label: "15 Minuten" },
  { value: 30, label: "30 Minuten" },
  { value: 60, label: "60 Minuten" },
  { value: 360, label: "6 Stunden" },
  { value: 720, label: "12 Stunden" },
];

export default function KueEinstellung({
  slot,
  onClose = () => {},
  onModulNameChange = () => {},
}: Props) {
  const dispatch = useDispatch();
  const {
    kueID,
    kueLimit1,
    kueDelay1,
    kueLimit2Low,
    kueLimit2High,
    kueLoopInterval,
    memoryInterval,
  } = useSelector((state: RootState) => state.kueDataSlice);

  const { isAdminLoggedIn } = useAdminAuth(true);

  const handleSaveWrapper = () => {
    const originalValues: OriginalValues = {
      kueID: [...(window.win_kueID ?? [])],
      isolationsgrenzwerte: [...(window.win_kueLimit1 ?? [])],
      verzoegerung: [...(window.win_kueDelay1 ?? [])],
      untereSchleifenGrenzwerte: [...(window.win_kueLimit2Low ?? [])],
      obereSchleifenGrenzwerte: [...(window.win_kueLimit2High ?? [])],
      schleifenintervall: [...(window.win_kueLoopInterval ?? [])],
      speicherintervall: [...(window.win_memoryInterval ?? [])],
    };

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

  const updateArray = (
    key: keyof RootState["kueDataSlice"],
    array: number[],
    value: number
  ) => {
    const updated = [...array];
    updated[slot] = value;
    dispatch(setKueData({ [key]: updated }));
  };

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

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

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

        <div>
          <label className="font-bold block mb-1">Speicherintervall</label>
          <select
            className="w-full border rounded p-1 text-sm"
            value={memoryInterval[slot] ?? ""}
            onChange={(e) =>
              updateArray(
                "memoryInterval",
                memoryInterval,
                parseInt(e.target.value, 10)
              )
            }
          >
            {memoryIntervalOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>
      </div>

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