"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.000000");
  const [factor, setFactor] = useState("1.000000");
  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(6)
          : selectedInput.offset || "0.000000"
      );
      setFactor(
        typeof selectedInput.factor === "number"
          ? selectedInput.factor.toFixed(6)
          : selectedInput.factor || "1.000000"
      );
      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 inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
      <div className="bg-white rounded shadow p-6 w-full max-w-md">
        <h2 className="text-lg font-semibold mb-4">
          Eingang {selectedInput.id} – Einstellungen
        </h2>

        <label className="block mb-2 text-sm font-medium">Bezeichnung</label>
        <input
          type="text"
          className="w-full border rounded px-3 py-1 mb-4"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

        <label className="block mb-2 text-sm font-medium">Offset</label>
        <input
          type="number"
          step="0.000001"
          className="w-full border rounded px-3 py-1 mb-4"
          value={offset}
          onChange={(e) => setOffset(e.target.value)}
        />

        <label className="block mb-2 text-sm font-medium">Faktor</label>
        <input
          type="number"
          step="0.000001"
          className="w-full border rounded px-3 py-1 mb-4"
          value={factor}
          onChange={(e) => setFactor(e.target.value)}
        />

        <label className="block mb-2 text-sm font-medium">Einheit</label>
        <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>

        <label className="block mb-2 text-sm font-medium">
          Loggerintervall (s)
        </label>
        <input
          type="number"
          className="w-full border rounded px-3 py-1 mb-4"
          value={loggerInterval}
          onChange={(e) => setLoggerInterval(e.target.value)}
        />

        <div className="flex justify-end gap-2">
          <button
            onClick={onClose}
            disabled={isSaving}
            className="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400"
          >
            Abbrechen
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            {isSaving ? "Speichern..." : "Speichern"}
          </button>
        </div>
      </div>
    </div>
  );
}
