"use client";

import React from "react";
import { Dialog } from "@headlessui/react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/redux/store";
import { setIsChartModalOpen } from "@/redux/slices/analogInputs/analogInputsUiSlice";
import AnalogInputsChart from "@/components/main/analogInputs/AnalogInputsChart";

export default function AnalogInputsChartModal({
  loading,
  setLoading,
}: {
  loading: boolean;
  setLoading: (v: boolean) => void;
}) {
  const dispatch = useDispatch();
  const isOpen = useSelector(
    (state: RootState) => state.analogInputsUi.isChartModalOpen
  );
  const selectedId = useSelector(
    (state: RootState) => state.analogInputsHistory.selectedId
  );

  if (!isOpen) return null;

  return (
    <Dialog
      open={isOpen}
      onClose={() => dispatch(setIsChartModalOpen(false))}
      className="relative z-[9999]"
    >
      {/* Backdrop */}
      <div className="fixed inset-0 bg-black/50" aria-hidden="true" />
      {/* Centered panel */}
      <div className="fixed inset-0 flex items-center justify-center p-4">
        <Dialog.Panel className="bg-white w-[95vw] h-[85vh] max-w-6xl rounded-xl shadow-xl border border-gray-200 p-4 flex flex-col">
          <div className="flex items-center justify-between mb-3">
            <Dialog.Title className="text-lg font-semibold text-gray-700">
              Messkurve Messwerteingang {selectedId ?? "–"}
            </Dialog.Title>
            <button
              className="text-xl text-gray-500 hover:text-gray-700"
              onClick={() => dispatch(setIsChartModalOpen(false))}
              aria-label="Modal schließen"
            >
              ✕
            </button>
          </div>
          <div className="flex-1 min-h-0">
            <AnalogInputsChart loading={loading} setLoading={setLoading} />
          </div>
        </Dialog.Panel>
      </div>
    </Dialog>
  );
}
