import { useState } from "react";
import { Box, Typography, Paper, Popover } from "@mui/material";
import { DateRange, Range, DateRangeProps } from "react-date-range";
import { format } from "date-fns";

import "react-date-range/dist/styles.css";
import "react-date-range/dist/theme/default.css";

import "./DateRangePicker.scss";

export const DateRangePicker = () => {
  const [range, setRange] = useState<Range[]>([
    {
      startDate: new Date(),
      endDate: new Date(),
      key: "selection",
    },
  ]);

  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

  const handleSelect: DateRangeProps["onChange"] = (ranges) => {
    if (ranges.selection) {
      setRange([ranges.selection]);
      if (ranges.selection.endDate !== ranges.selection.startDate) {
        setAnchorEl(null);
      }
    }
  };

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? "date-range-popover" : undefined;

  return (
    <Box className="date-range-picker">
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <Paper>
          <DateRange
            editableDateInputs={true}
            onChange={handleSelect}
            moveRangeOnFirstSelection={false}
            ranges={range}
          />
        </Paper>
      </Popover>

      <Box>
        <Typography
          onClick={handleClick}
          className="date-range-picker__date-typo"
        >
          {format(range[0].startDate ?? new Date(), "PPP")} -{" "}
          {format(range[0].endDate ?? new Date(), "PPP")}
        </Typography>
      </Box>
    </Box>
  );
};
