import React, { useState } from 'react';
import {
  Select,
  MenuItem,
  FormControl,
  Box,
  Backdrop,
  Paper
} from '@mui/material';
import PropTypes from 'prop-types';
import CustomDateRangePicker from './DateRangePicker.js';
import SingleDatePicker from './SingleDatePicker.js';
import './SmartDateSelector.css';

function SmartDateSelector({ onChange, onApply, dateType = 'range', initialValue = null, useSingleDate = false }) {
  const [selectedOption, setSelectedOption] = useState('current_date');
  const [customDateRange, setCustomDateRange] = useState(initialValue || null);
  const [showCustomPicker, setShowCustomPicker] = useState(false);

  // Calculate date ranges for preset options
  const getDateRange = (option) => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const date = now.getDate();

    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);

    const startOfWeek = new Date(now);
    startOfWeek.setDate(now.getDate() - now.getDay());
    const weekYear = startOfWeek.getFullYear();
    const weekMonth = startOfWeek.getMonth();
    const weekDate = startOfWeek.getDate();

    switch (option) {
      case 'current_date':
        return { 
          startDate: new Date(Date.UTC(year, month, date, 0, 0, 0, 0)), 
          endDate: new Date(Date.UTC(year, month, date + 1, 23, 59, 59, 999)), 
          displayLabel: 'Today' 
        };
      case 'current_week':
        return { 
          startDate: new Date(Date.UTC(weekYear, weekMonth, weekDate, 0, 0, 0, 0)), 
          endDate: new Date(Date.UTC(year, month, date, 23, 59, 59, 999)), 
          displayLabel: 'Current Week' 
        };
      case 'current_month':
        return { 
          startDate: new Date(Date.UTC(year, month, 1, 0, 0, 0, 0)), 
          endDate: new Date(Date.UTC(year, month, date, 23, 59, 59, 999)), 
          displayLabel: 'Current Month' 
        };
      default:
        return null;
    }
  };

  // Handle preset option selection
  const handleOptionChange = (event) => {
    const option = event.target.value;
    setSelectedOption(option);

    if (option === 'custom') {
      setShowCustomPicker(true);
    } else {
      const dateRange = getDateRange(option);
      setCustomDateRange(dateRange);
      setShowCustomPicker(false);
      
      if (onApply) {
        onApply(dateRange);
      }
    }
  };

  // Handle custom date selection from picker
  const handleCustomDateSelect = (date) => {
    if (useSingleDate) {
      setCustomDateRange(date);
    }
  };

  // Handle custom date range apply
  const handleCustomDateApply = (selectedRange) => {
    setCustomDateRange(selectedRange);
    
    if (useSingleDate) {
      // For single date picker, selectedRange is a Date object
      const dateToFormat = selectedRange instanceof Date ? selectedRange : new Date(selectedRange);
      if (Number.isNaN(dateToFormat.getTime())) {
        console.error('Invalid date:', selectedRange);
        return;
      }
    } else {
      // For date range picker, selectedRange has startDate and endDate
      if (!selectedRange?.startDate || !selectedRange?.endDate) {
        console.error('Invalid date range:', selectedRange);
        return;
      }
      const startDate = selectedRange.startDate instanceof Date ? selectedRange.startDate : new Date(selectedRange.startDate);
      const endDate = selectedRange.endDate instanceof Date ? selectedRange.endDate : new Date(selectedRange.endDate);
      
      if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
        console.error('Invalid dates in range:', selectedRange);
        return;
      }
    }

    if (onApply) {
      onApply(selectedRange);
    }
    
    setShowCustomPicker(false);
  };

  // Handle custom date picker close
  const handleCustomPickerClose = () => {
    setShowCustomPicker(false);
  };

  return (
    <Box className="smart-date-selector-wrapper">
      <FormControl sx={{ minWidth: 200 }} size="small">
        <Select
          value={selectedOption}
          onChange={handleOptionChange}
          className="smart-date-select"
          displayEmpty
          data-testid="smart-date-selector"
        >
          <MenuItem value="current_date">Today</MenuItem>
          <MenuItem value="current_week">Current Week</MenuItem>
          <MenuItem value="current_month">Current Month</MenuItem>
          <MenuItem value="custom">Custom</MenuItem>
        </Select>
      </FormControl>

      {/* Backdrop and Modal for Custom Date Picker */}
      <Backdrop
        open={showCustomPicker}
        onClick={handleCustomPickerClose}
        sx={{
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          zIndex: 1300
        }}
      />

      {showCustomPicker && (
        <Paper
          className="custom-date-picker-modal"
          elevation={3}
        >
          {useSingleDate ? (
            <SingleDatePicker
              onChange={handleCustomDateSelect}
              onApply={handleCustomDateApply}
              onClose={handleCustomPickerClose}
              selDate={customDateRange}
            />
          ) : (
            <CustomDateRangePicker
              onChange={handleCustomDateSelect}
              onApply={handleCustomDateApply}
              onClose={handleCustomPickerClose}
              selDate={customDateRange}
            />
          )}
        </Paper>
      )}
    </Box>
  );
}

SmartDateSelector.propTypes = {
  onChange: PropTypes.func,
  onApply: PropTypes.func.isRequired,
  dateType: PropTypes.oneOf(['range', 'single']),
  initialValue: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  useSingleDate: PropTypes.bool
};

export default SmartDateSelector;
