"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-[var(--color-surface)] border border-base rounded-xl shadow-xl w-[32rem] max-w-full p-0 flex flex-col">
        <header className="modal-header flex items-center justify-between px-6 py-4 border-b border-base">
          <h2 className="text-base font-bold text-fg">
            Einstellungen Messwerteingang {selectedInput.id}
          </h2>
          <button
            onClick={() => dispatch(setIsSettingsModalOpen(false))}
            className="icon-btn text-2xl"
            aria-label="Modal schließen"
            type="button"
          >
            <i className="bi bi-x-circle-fill" />
          </button>
        </header>
        <div className="modal-body-scroll px-6 py-5 flex-1 text-fg">
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <span className="font-normal text-fg-secondary">Bezeichnung:</span>
            <input
              type="text"
              className="border border-base rounded px-2 py-1 w-full bg-[var(--color-surface-alt)] text-fg"
              value={label}
              onChange={(e) => setLabel(e.target.value)}
            />
          </div>
          <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
            <span className="font-normal text-fg-secondary">Offset:</span>
            <input
              type="number"
              step="0.001"
              className="border border-base rounded px-2 py-1 w-full text-right bg-[var(--color-surface-alt)] text-fg"
              value={offset}
              onChange={(e) => setOffset(e.target.value)}
            />
          </div>
          <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
            <span className="font-normal text-fg-secondary">Faktor:</span>
            <input
              type="number"
              step="0.001"
              className="border border-base rounded px-2 py-1 w-full text-right bg-[var(--color-surface-alt)] text-fg"
              value={factor}
              onChange={(e) => setFactor(e.target.value)}
            />
          </div>
          <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
            <span className="font-normal text-fg-secondary">Einheit:</span>
            <Listbox value={unit} onChange={setUnit}>
              <div className="relative w-full">
                <Listbox.Button className="w-full border border-base px-2 py-1 rounded text-left bg-[var(--color-surface-alt)] text-fg flex justify-between items-center text-sm font-sans">
                  <span>{unit}</span>
                  <svg
                    className="w-5 h-5 text-muted"
                    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 border-base rounded bg-[var(--color-surface-alt)] shadow max-h-60 overflow-auto text-sm text-fg 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-base-muted"
                            : "text-fg"
                        }`
                      }
                    >
                      {opt}
                    </Listbox.Option>
                  ))}
                </Listbox.Options>
              </div>
            </Listbox>
          </div>
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <span className="font-normal text-fg-secondary">
              Speicherintervall:
            </span>
            <div className="relative w-full">
              <input
                type="number"
                className="border border-base rounded px-2 py-1 pr-20 w-full text-right bg-[var(--color-surface-alt)] text-fg"
                value={loggerInterval}
                onChange={(e) => setLoggerInterval(e.target.value)}
              />
              <span className="absolute right-2 top-1/2 transform -translate-y-1/2 text-muted text-sm">
                Minuten
              </span>
            </div>
          </div>
        </div>
        <footer className="px-6 py-4 border-t border-base flex justify-end">
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="btn-primary px-4 py-2 rounded flex items-center"
          >
            {isSaving ? "Speichern..." : "Speichern"}
          </button>
        </footer>
      </div>
    </div>
  );
}
