"use client";

import React, { useState, useEffect } from "react";

declare global {
  interface Window {
    win_tdrActive?: number[];
  }
}

interface Props {
  slot: number;
}

export default function TdrEinstellung({ slot }: Props) {
  const [tdrActive, setTdrActive] = useState(false);
  const [params, setParams] = useState({
    verstarkung: "",
    pulsweite: "",
    trigger: "",
  });

  useEffect(() => {
    if (
      typeof window !== "undefined" &&
      Array.isArray(window.win_tdrActive) &&
      typeof window.win_tdrActive[slot] !== "undefined"
    ) {
      const status = parseInt(String(window.win_tdrActive[slot]));
      setTdrActive(status === 1);
    } else {
      console.warn("⚠️ win_tdrActive ist nicht definiert oder Slot ungültig");
    }
  }, [slot]);

  return (
    <div className="space-y-4 text-sm laptop:text-base">
      <h2 className="text-base laptop:text-lg font-semibold">
        TDR-Einstellung – Steckplatz {slot + 1}
      </h2>

      <div className="flex items-center gap-3">
        <span className="text-sm font-medium">TDR-Funktion:</span>
        <button
          type="button"
          role="switch"
          aria-checked={tdrActive}
          onClick={() => setTdrActive(!tdrActive)}
          className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 ${
            tdrActive ? "bg-green-500" : "bg-gray-300"
          }`}
        >
          <span
            className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform duration-200 ${
              tdrActive ? "translate-x-6" : "translate-x-1"
            }`}
          />
        </button>
        <span className="text-sm text-gray-600">
          {tdrActive ? "aktiviert" : "deaktiviert"}
        </span>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <input
          placeholder="Verstärkung"
          value={params.verstarkung}
          onChange={(e) =>
            setParams({ ...params, verstarkung: e.target.value })
          }
          className="border px-2 py-1 rounded"
        />
        <input
          placeholder="Pulsweite"
          value={params.pulsweite}
          onChange={(e) => setParams({ ...params, pulsweite: e.target.value })}
          className="border px-2 py-1 rounded"
        />
        <input
          placeholder="Trigger"
          value={params.trigger}
          onChange={(e) => setParams({ ...params, trigger: e.target.value })}
          className="border px-2 py-1 rounded"
        />
      </div>
    </div>
  );
}
