"use client";
import { useState, useEffect } from "react";
import ReactModal from "react-modal";
import KueEinstellung from "./KueEinstellung";
import TdrEinstellung from "./TdrEinstellung";
import KvzModalView from "./KvzModalView";
import Knotenpunkte from "./Knotenpunkte";

interface KueModalProps {
  showModal: boolean;
  onClose: () => void;
  slot: number;
  onModulNameChange: (id: string) => void;
}

declare global {
  interface Window {
    __lastKueTab?: "kue" | "tdr" | "kvz" | "knoten";
    kabelModalOpen?: boolean;
  }
}

export default function KueModal({ showModal, onClose, slot }: KueModalProps) {
  const [activeTab, setActiveTab] = useState<"kue" | "tdr" | "kvz" | "knoten">(
    () => {
      if (typeof window !== "undefined" && window.__lastKueTab) {
        return window.__lastKueTab;
      }
      return "kue";
    }
  );

  useEffect(() => {
    if (typeof window !== "undefined") {
      window.__lastKueTab = activeTab;
    }
  }, [activeTab]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      window.kabelModalOpen = showModal;
    }
  }, [showModal]);

  return (
    <ReactModal
      isOpen={showModal}
      onRequestClose={onClose}
      shouldCloseOnOverlayClick
      ariaHideApp={false}
      style={{
        overlay: {
          backgroundColor: "rgba(0,0,0,0.55)",
          zIndex: 100,
          backdropFilter: "blur(2px)",
        },
        content: {
          inset: "50% auto auto 50%",
          transform: "translate(-50%, -50%)",
          width: "min(900px,92vw)",
          // Feste / konsistente Höhe, unabhängig vom Tab-Inhalt
          // Wenn Viewport kleiner ist, begrenze auf 80vh
          height: "min(640px, 80vh)",
          maxHeight: "80vh",
          padding: 0,
          border: "1px solid var(--color-border)",
          background: "var(--color-surface)",
          borderRadius: "12px",
          overflow: "hidden",
          display: "flex",
          flexDirection: "column",
        },
      }}
      contentLabel={`Einstellungen KÜ ${slot + 1}`}
    >
      <div className="modal-header">
        <h2 className="text-sm font-semibold tracking-wide text-fg">
          Einstellungen KÜ {slot + 1}
        </h2>
        <button
          onClick={onClose}
          className="icon-btn"
          aria-label="Modal schließen"
          type="button"
        >
          <i className="bi bi-x-lg text-base" />
        </button>
      </div>

      <div className="flex justify-start bg-surface-alt px-3 pt-2 gap-2 border-b border-base">
        {[
          { label: "Allgemein", key: "kue" as const },
          { label: "TDR", key: "tdr" as const },
          { label: "KVz", key: "kvz" as const },
          { label: "Knotenpunkte", key: "knoten" as const },
        ].map(({ label, key }) => {
          const isActive = activeTab === key;
          return (
            <button
              key={key}
              type="button"
              onClick={() => setActiveTab(key)}
              className={`tab-btn ${isActive ? "tab-btn-active" : ""}`}
              aria-current={isActive ? "page" : undefined}
            >
              {label}
            </button>
          );
        })}
      </div>
      {/* Einheitliche Body-Höhe mit internem Scroll statt dynamischer Außenhöhe */}
      <div className="modal-body-scroll px-5 py-4 flex-1 text-fg overflow-y-auto">
        {activeTab === "kue" && (
          <KueEinstellung
            slot={slot}
            showModal={showModal}
            onModulNameChange={(id) => console.log("Modulname geändert:", id)}
            onClose={onClose}
          />
        )}
        {activeTab === "tdr" && (
          <TdrEinstellung slot={slot} onClose={onClose} />
        )}
        {activeTab === "kvz" && <KvzModalView slot={slot} onClose={onClose} />}
        {activeTab === "knoten" && (
          <Knotenpunkte slot={slot} onClose={onClose} />
        )}
      </div>
    </ReactModal>
  );
}
