import DatePickerRanges from "../../utils/DatePickerRanges";
import { DatePicker } from "antd";
import dayjs from "../../utils/day";
import queryString from "query-string";
import { useLocation, useNavigate } from "react-router-dom";

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

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

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

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