import { Dialog, DialogTitle, DialogContent, Typography, Stack, Button, DialogActions, Paper } from '@mui/material';

import { DateRangePicker } from 'mui-daterange-picker';
import dayjs from 'dayjs';

import { addDays, addWeeks, addMonths, startOfWeek, endOfWeek, startOfMonth, endOfMonth } from 'date-fns';

export default function DateFilterDialog({ open, onClose, onApply }) {
  const 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: addDays(new Date(), -7), 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)) }
  ];

  const handleSelect = (range) => {
    if (!range?.startDate || !range?.endDate) return;
    onApply({
      startDate: dayjs(range.startDate).format('YYYY-MM-DD'),
      endDate: dayjs(range.endDate).format('YYYY-MM-DD'),
      label: range.label || ''
    });
    onClose();
  };

  return (
    <Dialog open={open} onClose={() => onclose()} fullWidth maxWidth="sm">
      <DialogTitle disableTypography>
        <Stack display="flex" flexDirection="row" justifyContent="space-between" alignItems="center" sx={{ width: '100%' }}>
          <Typography variant="h4">Select Date Range</Typography>
        </Stack>
      </DialogTitle>
      <DialogContent
        sx={{
          '& .MuiPaper-root': {
            boxShadow: 'none !important'
          }
        }}
      >
        <DateRangePicker open={open} toggle={onClose} definedRanges={definedRanges} onChange={handleSelect} closeOnClickOutside={false} />
      </DialogContent>
      <DialogActions>
        <Button variant="contained" onClick={onClose} sx={{ cursor: 'pointer' }}>
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}
