import React, { useEffect } from "react";
import DatePicker from "react-datepicker";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import {
  setVonDatum,
  setBisDatum,
} from "../../../../../../redux/slices/kabelueberwachungChartSlice";
import "react-datepicker/dist/react-datepicker.css";

interface DateRangePickerProps {
  minDate: string;
  maxDate: string;
}

const DateRangePicker: React.FC<DateRangePickerProps> = ({
  minDate,
  maxDate,
}) => {
  const dispatch = useDispatch();

  const reduxVonDatum = useSelector(
    (state: RootState) => state.kabelueberwachungChart.vonDatum
  );
  const reduxBisDatum = useSelector(
    (state: RootState) => state.kabelueberwachungChart.bisDatum
  );

  const today = new Date();
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(today.getDate() - 30);

  // Redux speichert ISO ("YYYY-MM-DD") => Für DatePicker geeignet
  const parseISODate = (isoDate: string) => {
    const [year, month, day] = isoDate.split("-").map(Number);
    return new Date(year, month - 1, day);
  };

  useEffect(() => {
    if (!reduxVonDatum)
      dispatch(setVonDatum(thirtyDaysAgo.toISOString().split("T")[0]));
    if (!reduxBisDatum)
      dispatch(setBisDatum(today.toISOString().split("T")[0]));
  }, [dispatch, reduxVonDatum, reduxBisDatum]);

  return (
    <div className="flex space-x-4 items-center">
      <div className="flex items-center space-x-2">
        <label className="block text-sm font-semibold">Von</label>
        <DatePicker
          selected={reduxVonDatum ? parseISODate(reduxVonDatum) : thirtyDaysAgo}
          onChange={(date) => {
            if (date) {
              dispatch(setVonDatum(date.toISOString().split("T")[0]));
            }
          }}
          selectsStart
          startDate={
            reduxVonDatum ? parseISODate(reduxVonDatum) : thirtyDaysAgo
          }
          endDate={reduxBisDatum ? parseISODate(reduxBisDatum) : today}
          minDate={new Date(minDate)}
          maxDate={new Date(maxDate)}
          dateFormat="dd.MM.yyyy"
          className="border px-2 py-1 rounded"
        />
      </div>

      <div className="flex items-center space-x-2">
        <label className="block text-sm font-semibold">Bis</label>
        <DatePicker
          selected={reduxBisDatum ? parseISODate(reduxBisDatum) : today}
          onChange={(date) => {
            if (date) {
              dispatch(setBisDatum(date.toISOString().split("T")[0]));
            }
          }}
          selectsEnd
          startDate={
            reduxVonDatum ? parseISODate(reduxVonDatum) : thirtyDaysAgo
          }
          endDate={reduxBisDatum ? parseISODate(reduxBisDatum) : today}
          minDate={new Date(minDate)}
          maxDate={new Date(maxDate)}
          dateFormat="dd.MM.yyyy"
          className="border px-2 py-1 rounded"
        />
      </div>
    </div>
  );
};

export default DateRangePicker;
