import "./CalendarComponent.css";
import chevron from "images/icons/ChevronRight.svg";

import * as moment from "moment";
import "moment/locale/ru";
import { motion, useAnimationControls } from "framer-motion";

import { useState, useEffect } from "react";

import { planSlice } from "store/reducers/planSlice";
import { useAppDispatch, useAppSelector } from "hooks/redux";
import { variantsCalendar } from "utils/animationProps.js";

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

  const [calendar, setCalendar] = useState([]);
  const [value, setValue] = useState(time);
  const currDate = time;
  const startDay = value.clone().startOf("month").startOf("week");
  const endDay = value.clone().endOf("month").endOf("week");
  const weekDays = ["ПН", "ВT", "СР", "ЧТ", "ПТ", "СБ", "ВС"];

  useEffect(() => {
    controls.start({
      opacity: 1,
    });
  }, [nextMonth, prevMonth]);

  useEffect(() => {
    const day = startDay.clone().subtract("1", "day");
    const a = [];
    while (day.isBefore(endDay, "day")) {
      a.push(
        Array(7)
          .fill(0)
          .map(() => day.add(1, "day").clone())
      );
    }
    setCalendar(a);
  }, [value]);

  function prevMonth() {
    return value.clone().subtract(1, "month");
  }

  function nextMonth() {
    return value.clone().add(1, "month").startOf("month");
  }

  function thisMonth() {
    return value.isSame(new Date(), "month");
  }

  function hide(day: any) {
    if (value.isSame(day, "month")) {
      if (currDate.isSame(day, "day")) {
        const cellClass = "calendar-cell_active calendar-cell";
        return cellClass;
      }
      return "calendar-cell calendar-cell_day";
    } else {
      return "calendar-cell-none";
    }
  }

  const handleValue = (day: moment.Moment) => {
    const temp = currDate.clone().subtract(1, "day");
    if (day.isBefore(temp)) {
      return;
    } else {
      dispatch(
        handleNavigation({
          isDone: false,
          isCalendar: false,
          isTimepicker: true,
          isForm: false,
        })
      );
      dispatch(handleTimeValue(day));
    }
  };

  return (
    <div className="calendar-container">
      <h3 className="plan-title">Выберите дату.</h3>
      <div className="calendar">
        <div className="calendar-header">
          <img
            alt="prev-mouth"
            onClick={() => !thisMonth() && setValue(prevMonth())}
            className="calendar-nav calendar-nav-left"
            src={chevron}
          ></img>
          <span className="calendar-date">
            {value.format("MMMM")}, {value.format("YYYY")}
          </span>
          <img
            alt="next-mouth"
            onClick={() => setValue(nextMonth())}
            className="calendar-nav"
            src={chevron}
          ></img>
        </div>
        <div className="weekday-table">
          {weekDays.map((day, i) => (
            <div key={i} className="calendar-cell">
              {day}
            </div>
          ))}
        </div>
        {calendar.map((week, i) => (
          <motion.div
            initial="hidden"
            animate="visible"
            variants={variantsCalendar}
            key={Math.random()}
            className="calendar-table"
          >
            {week.map((day: any, i: number) => (
              <div
                key={i}
                onClick={() => handleValue(day)}
                className={hide(day)}
              >
                {day.format("D")}
              </div>
            ))}
          </motion.div>
        ))}
      </div>
    </div>
  );
};
