"use client"; // TDRChartView.tsx

import React, { useEffect } from "react";
import ReactModal from "react-modal";
import TDRChart from "./TDRChart";
import TDRChartActionBar from "./TDRChartActionBar";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "@/redux/store";
import {
  setChartOpen,
  setFullScreen,
  setSlotNumber,
  setVonDatum,
  setBisDatum,
  setSelectedMode,
  setSelectedSlotType,
  setChartTitle,
} from "@/redux/slices/kabelueberwachungChartSlice";
import { resetBrushRange } from "@/redux/slices/brushSlice";
import {
  setSelectedSlot,
  setActiveMode,
} from "@/redux/slices/kueChartModeSlice";
import { Listbox } from "@headlessui/react";
import Report from "../IsoMeasurementChart/Report";

interface TDRChartViewProps {
  isOpen: boolean;
  onClose: () => void;
  slotIndex: number;
}

const TDRChartView: React.FC<TDRChartViewProps> = ({
  isOpen,
  onClose,
  slotIndex,
}) => {
  const dispatch = useDispatch<AppDispatch>();
  const { isFullScreen, chartTitle } = useSelector(
    (s: RootState) => s.kabelueberwachungChartSlice
  );

  // Initialize defaults when opening
  useEffect(() => {
    if (!isOpen) return;
    const today = new Date();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(today.getDate() - 30);
    const toISO = (date: Date) => date.toLocaleDateString("sv-SE");

    dispatch(setActiveMode("TDR"));
    dispatch(setSelectedSlot(slotIndex));
    dispatch(setSlotNumber(slotIndex));

    dispatch(setVonDatum(toISO(thirtyDaysAgo)));
    dispatch(setBisDatum(toISO(today)));

    if (chartTitle !== "Messkurve" && chartTitle !== "Meldungen") {
      dispatch(setChartTitle("Messkurve"));
    }
    // Only run when opened or slot changes or chartTitle invalid
  }, [isOpen, slotIndex, chartTitle, dispatch]);

  const handleClose = () => {
    // Reset generic chart slice to DIA1 isolationswiderstand defaults (same pattern as other modals)
    const today = new Date();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(today.getDate() - 30);
    const toISO = (date: Date) => date.toLocaleDateString("sv-SE");
    dispatch(setVonDatum(toISO(thirtyDaysAgo)));
    dispatch(setBisDatum(toISO(today)));
    dispatch(setSelectedMode("DIA1"));
    dispatch(setSelectedSlotType("isolationswiderstand"));
    dispatch(setChartOpen(false));
    dispatch(setFullScreen(false));
    dispatch(resetBrushRange());
    onClose();
  };

  const toggleFullScreen = () => dispatch(setFullScreen(!isFullScreen));

  return (
    <ReactModal
      isOpen={isOpen}
      onRequestClose={handleClose}
      ariaHideApp={false}
      style={{
        overlay: {
          backgroundColor: "rgba(0,0,0,0.55)",
          backdropFilter: "blur(2px)",
        },
        content: {
          inset: "50% auto auto 50%",
          transform: "translate(-50%, -50%)",
          width: isFullScreen ? "90vw" : "72rem",
          height: isFullScreen ? "90vh" : "38rem",
          padding: 0,
          border: "1px solid var(--color-border)",
          background: "var(--color-surface)",
          borderRadius: "14px",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        },
      }}
      contentLabel="TDR Messung"
    >
      <header className="modal-header relative pr-56">
        <h3 className="text-sm font-semibold tracking-wide">TDR-Messung</h3>
        <div className="absolute top-2 right-2 flex gap-2">
          <button
            onClick={toggleFullScreen}
            className="icon-btn"
            aria-label={isFullScreen ? "Vollbild verlassen" : "Vollbild"}
            type="button"
          >
            <i
              className={
                isFullScreen
                  ? "bi bi-fullscreen-exit"
                  : "bi bi-arrows-fullscreen"
              }
            />
          </button>
          <button
            onClick={handleClose}
            className="icon-btn"
            aria-label="Schließen"
            type="button"
          >
            <i
              style={{
                background: "transparent",
                border: "none",
                fontSize: "1.5rem",
                cursor: "pointer",
              }}
              className="bi bi-x-circle-fill"
            />
          </button>
        </div>
        <div className="absolute top-2 right-28">
          <Listbox
            value={chartTitle}
            onChange={(value: "Messkurve" | "Meldungen") =>
              dispatch(setChartTitle(value))
            }
          >
            <div className="relative w-40">
              <Listbox.Button className="dropdown-surface w-full flex items-center justify-between h-8">
                <span className="dropdown-text-fix">{chartTitle}</span>
                <i className="bi bi-chevron-down text-sm opacity-70" />
              </Listbox.Button>
              <Listbox.Options className="dropdown-options absolute z-50 mt-1 w-full max-h-60 overflow-auto text-sm">
                {(["Messkurve", "Meldungen"] as const).map((option) => (
                  <Listbox.Option
                    key={option}
                    value={option}
                    className={({ selected, active }) =>
                      `px-3 py-1.5 cursor-pointer rounded-sm m-0.5 ${
                        selected
                          ? "dropdown-option-active"
                          : active
                          ? "dropdown-option-hover"
                          : ""
                      }`
                    }
                  >
                    {option}
                  </Listbox.Option>
                ))}
              </Listbox.Options>
            </div>
          </Listbox>
        </div>
      </header>
      <div className="flex flex-col flex-1 p-3 gap-3">
        {/* Action Bar (wie bei ISO / Loop) */}
        <TDRChartActionBar />
        <div className="flex-1 relative">
          {chartTitle === "Messkurve" ? (
            <TDRChart isFullScreen={isFullScreen} />
          ) : (
            <Report moduleType="TDR" />
          )}
        </div>
      </div>
    </ReactModal>
  );
};

export default TDRChartView;
