"use client";

import React, { useEffect, useState } from "react";
import { Listbox } from "@headlessui/react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/redux/store";
import { setIsSettingsModalOpen } from "@/redux/slices/analogInputs/analogInputsUiSlice";

import type { AnalogInput } from "@/types/analogInput"; // 👈 Importiere den Typ (jetzt definiert und exportiert)

export default function AnalogInputsSettingsModal() {
  const dispatch = useDispatch();

  const isOpen = useSelector(
    (state: RootState) => state.analogInputsUi.isSettingsModalOpen
  );

  const selectedInput = useSelector<RootState, AnalogInput | null>(
    (state) => state.selectedAnalogInput
  );

  const [label, setLabel] = useState("");
  const [offset, setOffset] = useState("0.000");
  const [factor, setFactor] = useState("1.000");
  const [loggerInterval, setLoggerInterval] = useState("9");
  const [unit, setUnit] = useState("V");
  const [isSaving, setIsSaving] = useState(false);

  const unitOptions = ["V", "mA", "°C", "bar", "%"];

  useEffect(() => {
    if (selectedInput && isOpen) {
      setLabel(selectedInput.label || "");
      setOffset(
        typeof selectedInput.offset === "number"
          ? selectedInput.offset.toFixed(3)
          : selectedInput.offset || "0.000"
      );
      setFactor(
        typeof selectedInput.factor === "number"
          ? selectedInput.factor.toFixed(3)
          : selectedInput.factor || "1.000"
      );
      setLoggerInterval(selectedInput.loggerInterval || "9");
      setUnit(selectedInput.unit || "V");
    }
  }, [selectedInput, isOpen]);

  if (!isOpen || !selectedInput) return null;

  const handleSave = async () => {
    setIsSaving(true);

    const slot = selectedInput.id;
    const isDev = window.location.hostname === "localhost";

    const offsetParam = offset.replace(",", ".");
    const factorParam = factor.replace(",", ".");
    const loggerParam = loggerInterval;
    const acn = encodeURIComponent(label);
    const acu = encodeURIComponent(unit);

    const url = `/CPL?/Service/ae.ACP&ACN${slot}=${acn}&ACO${slot}=${offsetParam}&ACF${slot}=${factorParam}&ACL${slot}=${loggerParam}&ACU${slot}=${acu}`;

    try {
      if (isDev) {
        await fetch("/api/cpl/updateAnalogInputsSettingsHandler", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            updates: [
              { key: "win_analogInputsLabels", index: slot - 1, value: label },
              {
                key: "win_analogInputsOffset",
                index: slot - 1,
                value: parseFloat(offsetParam),
              },
              {
                key: "win_analogInputsFactor",
                index: slot - 1,
                value: parseFloat(factorParam),
              },
              { key: "win_analogInputsUnits", index: slot - 1, value: unit },
              {
                key: "win_analogInputsLoggerIntervall",
                index: slot - 1,
                value: parseInt(loggerParam),
              },
            ],
          }),
        });
        alert("Mockdaten gespeichert.");
      } else {
        const result = await fetch(url);
        if (!result.ok) throw new Error("Fehler bei CGI-Aufruf");
        alert("Einstellungen gespeichert (Produktion).");
      }

      dispatch(setIsSettingsModalOpen(false));
      location.reload();
    } catch (err) {
      alert("Fehler beim Speichern.");
      console.error(err);
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex justify-center items-center z-50">
      <div className="bg-white rounded-lg shadow-lg p-6 w-1/2 max-w-lg">
        <div className="mb-4 border-b pb-2 flex justify-between items-center">
          <h2 className="text-base font-bold">
            Einstellungen Messwerteingang {selectedInput.id}
          </h2>
          <button
            onClick={() => dispatch(setIsSettingsModalOpen(false))}
            className="text-2xl hover:text-gray-400"
            aria-label="Modal schließen"
          >
            <i className="bi bi-x-circle-fill"></i>
          </button>
        </div>

        {/* Bezeichnung */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3">
          <span className="font-normal">Bezeichnung:</span>
          <input
            type="text"
            className="w-full border rounded px-3 py-1 mb-4"
            value={label}
            onChange={(e) => setLabel(e.target.value)}
          />
        </div>

        {/* Offset */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
          <span className="font-normal">Offset:</span>
          <input
            type="number"
            step="0.001"
            className="border border-gray-300 rounded px-2 py-1 w-full text-right"
            value={offset}
            onChange={(e) => setOffset(e.target.value)}
          />
        </div>

        {/* Faktor */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
          <span className="font-normal">Faktor:</span>
          <input
            type="number"
            step="0.001"
            className="border border-gray-300 rounded px-2 py-1 w-full text-right"
            value={factor}
            onChange={(e) => setFactor(e.target.value)}
          />
        </div>

        {/* Einheit */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
          <span className="font-normal">Einheit:</span>
          <Listbox value={unit} onChange={setUnit}>
            <div className="relative w-full">
              <Listbox.Button className="w-full border px-3 py-1 rounded text-left bg-white flex justify-between items-center text-sm text-gray-900 font-sans">
                <span>{unit}</span>
                <svg
                  className="w-5 h-5 text-gray-400"
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                  aria-hidden="true"
                >
                  <path
                    fillRule="evenodd"
                    d="M5.23 7.21a.75.75 0 011.06.02L10 10.585l3.71-3.355a.75.75 0 111.02 1.1l-4.25 3.85a.75.75 0 01-1.02 0l-4.25-3.85a.75.75 0 01.02-1.06z"
                    clipRule="evenodd"
                  />
                </svg>
              </Listbox.Button>
              <Listbox.Options className="absolute z-50 mt-1 w-full border rounded bg-white shadow max-h-60 overflow-auto text-sm text-gray-900 font-sans">
                {unitOptions.map((opt) => (
                  <Listbox.Option
                    key={opt}
                    value={opt}
                    className={({ selected, active }) =>
                      `px-4 py-1 cursor-pointer ${
                        selected
                          ? "bg-littwin-blue text-white font-medium"
                          : active
                          ? "bg-gray-200"
                          : "text-gray-900"
                      }`
                    }
                  >
                    {opt}
                  </Listbox.Option>
                ))}
              </Listbox.Options>
            </div>
          </Listbox>
        </div>

        {/* Speicherintervall */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3">
          <span className="font-normal">Speicherintervall:</span>
          <div className="relative w-full">
            <input
              type="number"
              className="border rounded px-2 py-1 pr-20 w-full text-right"
              value={loggerInterval}
              onChange={(e) => setLoggerInterval(e.target.value)}
            />
            <span className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm">
              Minuten
            </span>
          </div>
        </div>

        {/* Speichern-Button */}
        <div className="flex justify-end gap-2 mt-6">
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="bg-littwin-blue text-white px-4 py-2 rounded flex items-center"
          >
            {isSaving ? "Speichern..." : "Speichern"}
          </button>
        </div>
      </div>
    </div>
  );
}
