"use client"; // /components/main/analogeEingaenge/AnalogInputsSettingsModal.tsx
import React, { useEffect, useState } from "react";

interface Props {
  selectedInput: any;
  isOpen: boolean;
  onClose: () => void;
}

export default function AnalogInputSettingsModal({
  selectedInput,
  isOpen,
  onClose,
}: Props) {
  const [name, setName] = useState("");
  const [offset, setOffset] = useState("0.000");
  const [factor, setFactor] = useState("1.000");
  const [loggerInterval, setLoggerInterval] = useState("10");
  const [unit, setUnit] = useState("V");
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    if (selectedInput && isOpen) {
      setName(selectedInput.name || "");
      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 !== undefined
          ? selectedInput.loggerInterval.toString()
          : "10"
      );
      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(name);
    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/updateAnalogInputsSettingsAPIHandler", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            updates: [
              { key: "win_analogInputsNames", index: slot - 1, value: name },
              {
                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).");
      }

      onClose();
      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={onClose}
            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">
          <div>
            <span className="font-normal">Bezeichnung:</span>
          </div>
          <div>
            <input
              type="text"
              className="w-full border rounded px-3 py-1 mb-4"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
        </div>
        {/* Offset */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
          <div>
            <span className="font-normal">Offset:</span>
          </div>
          <div>
            <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>
        </div>
        {/* Faktor */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3 mb-4">
          <div>
            <span className="font-normal">Faktor:</span>
          </div>
          <div>
            <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>
        </div>
        {/* Einheit  */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-3">
          <div>
            <span className="font-normal">Einheit:</span>
          </div>
          <div>
            <select
              className="w-full border rounded px-3 py-1 mb-4"
              value={unit}
              onChange={(e) => setUnit(e.target.value)}
            >
              <option value="V">V</option>
              <option value="mA">mA</option>
              <option value="°C">°C</option>
              <option value="bar">bar</option>
              <option value="%">%</option>
            </select>
          </div>
        </div>
        {/* Loggerintervall/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>

        <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>
  );
}
