import DatePickerRanges from "../../utils/DatePickerRanges";
import { DatePicker } from "antd";
import moment from "moment";
import queryString from "query-string";
import React from "react";
import { useHistory, useLocation } from "react-router-dom";

export default function TimeTicketsDatesSelector() {
  const searchParams = queryString.parse(useLocation().search);
  const { start, end } = searchParams;
  const history = useHistory();

  const handleChange = (dates) => {
    if (dates) {
      const [start, end] = dates;

      if (!!start && !!end) {
        history.push({
          search: queryString.stringify({
            ...searchParams,
            start: start.format("YYYY-MM-DD"),
            end: end.format("YYYY-MM-DD"),
          }),
        });
      }
    } else {
      history.push({
        search: queryString.stringify({
          ...searchParams,
          start: null,
          end: null,
        }),
      });
    }
  };

  return (
    <DatePicker.RangePicker
      defaultValue={[
        start ? moment(start) : moment().startOf("week").subtract(7, "days"),
        end ? moment(end) : moment().endOf("week"),
      ]}
      format="MM/DD/YYYY"
      ranges={DatePickerRanges}
      onCalendarChange={handleChange}
    />
  );
}
