import React, { useState } from 'react';
import { Dialog, DialogTitle, DialogContent, Button, Stack, Typography } from '@mui/material';
import { DateRangePicker } from 'mui-daterange-picker';
import dayjs from 'dayjs';
import { addDays, addWeeks, startOfWeek, endOfWeek, startOfMonth, endOfMonth, addMonths } from 'date-fns';

const DateFilterDialog = ({ open, onClose, onSelect }) => {
  const [selectedRange, setSelectedRange] = useState(null);

  const handleDateChange = (range) => {
    setSelectedRange({
      startDate: dayjs(range.startDate).format('YYYY-MM-DD'),
      endDate: dayjs(range.endDate).format('YYYY-MM-DD'),
      label: range.label || 'custom'
    });
  };

  return (
    <Dialog open={open} onClose={onClose}>
      <DialogTitle align="left">
        <Typography variant="h4">Select Filter Options</Typography>
      </DialogTitle>

      <DialogContent sx={{ width: '100%' }} className="datedialog">
        <DateRangePicker
          open={open}
          toggle={onClose}
          id="daterange1"
          onChange={handleDateChange}
          definedRanges={[
            { label: 'Today', startDate: new Date(), endDate: new Date() },
            { label: 'Yesterday', startDate: addDays(new Date(), -1), endDate: addDays(new Date(), -1) },
            { label: 'Tomorrow', startDate: addDays(new Date(), +1), endDate: addDays(new Date(), +1) },
            { label: 'This Week', startDate: startOfWeek(new Date()), endDate: endOfWeek(new Date()) },
            { label: 'Last Week', startDate: startOfWeek(addWeeks(new Date(), -1)), endDate: endOfWeek(addWeeks(new Date(), -1)) },
            { label: 'Last 7 Days', startDate: addWeeks(new Date(), -1), endDate: new Date() },
            { label: 'This Month', startDate: startOfMonth(new Date()), endDate: endOfMonth(new Date()) },
            { label: 'Last Month', startDate: startOfMonth(addMonths(new Date(), -1)), endDate: endOfMonth(addMonths(new Date(), -1)) }
          ]}
        />
      </DialogContent>

      <Stack direction="row" justifyContent="flex-end" sx={{ width: '100%', p: 2 }}>
        <Button
          variant="contained"
          size="small"
          onClick={() => {
            // If no date selected → close dialog only
            if (!selectedRange) {
              onClose();
              return;
            }

            // If date selected → return range + close
            onSelect(selectedRange);
            onClose();
          }}
        >
          OK
        </Button>
      </Stack>
    </Dialog>
  );
};

export default DateFilterDialog;
