import chevron from "images/icons/ChevronLeft.svg";
import "./TimepickerComponent.css";

import { planSlice } from "store/reducers/planSlice";
import { useAppDispatch, useAppSelector } from "hooks/redux";

import { useEffect, useState } from "react";

export const TimepickerComponent: React.FC<any> = ({ time }) => {
  const dispatch = useAppDispatch();
  const { handleNavigation, handleTimeValue } = planSlice.actions;

  const [timePicker, settimePicker] = useState([]);
  const startTime = time.clone().hours(8).minutes(0);
  const endTime = time.clone().hours(19).minutes(0);

  useEffect(() => {
    const temp = startTime.clone().subtract("30", "minute");
    const a = [];
    while (temp.isBefore(endTime, "minute")) {
      a.push(
        Array(8)
          .fill(0)
          .map(() => temp.add(30, "minutes").clone())
      );
    }
    settimePicker(a);
  }, [time]);

  const handleValue = (time: moment.Moment) => {
    dispatch(
      handleNavigation({
        isDone: false,
        isCalendar: false,
        isTimepicker: false,
        isForm: true,
      })
    );
    dispatch(handleTimeValue(time));
  };

  const handleReturn = () => {
    dispatch(
      handleNavigation({
        isDone: false,
        isCalendar: true,
        isTimepicker: false,
        isForm: false,
      })
    );
  };
  return (
    <div className="calendar-container">
      <h3 className="plan-title">Выберите время.</h3>
      <button
        onClick={() => handleReturn()}
        style={{ width: "120px", padding: "4px 16px 4px 4px", height: "32px" }}
        className="button button-type-small button-plan"
      >
        <img src={chevron}></img>
        Выбор даты
      </button>
      <div className="calendar">
        <div className="calendar-header">
          <span className="calendar-date">{time.format("DD MMMM")}</span>
        </div>
        {timePicker.map((day, i) => (
          <div key={i} className="timepicker-table">
            {day.map((time: any, i: number) => (
              <div
                onClick={() => handleValue(time)}
                key={i}
                className="calendar-cell timepicker-cell"
              >
                {time.format("LT")}
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
};
