import React, { useState, useRef, useEffect } from "react";
import PropTypes from "prop-types";
import { Box, Select, MenuItem } from "@mui/material";
import CustomDateRangePicker from "./DateRangePicker.js";
import SingleDatePicker from "./SingleDatePicker.js";
import { format } from "date-fns";
import { getDefaultDateRange } from "../constants/dateUtils.js";

const DateFilterDropdown = ({
  onChange,
  initialFilter = "Today",
  isRangePicker = true,
  dateFormat = "MM/dd/yyyy",
  placeholder = "Select Date Range",
}) => {
  

  const getToday = () => {
    const now = new Date();

    if (!isRangePicker) return now;

    const year = now.getFullYear();
    const month = now.getMonth();
    const date = now.getDate();

    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)),
    };
  };

  const getWeek = () => {
    if (!isRangePicker) return new Date();

    const today = new Date();
    const first = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    first.setDate(today.getDate() - today.getDay());

    const last = new Date(first.getFullYear(), first.getMonth(), first.getDate());
    last.setDate(first.getDate() + 6);

    return {
      startDate: new Date(Date.UTC(first.getFullYear(), first.getMonth(), first.getDate(), 0, 0, 0, 0)),
      endDate: new Date(Date.UTC(last.getFullYear(), last.getMonth(), last.getDate(), 23, 59, 59, 999)),
    };
  };

  const getMonth = () => {
    if (!isRangePicker) return new Date();

    const today = new Date();

    return {
      startDate: new Date(Date.UTC(today.getFullYear(), today.getMonth(), 1, 0, 0, 0, 0)),
      endDate: new Date(Date.UTC(
        today.getFullYear(),
        today.getMonth() + 1,
        0,
        23,
        59,
        59,
        999
      )),
    };
  };

  // Initialize with appropriate date range based on initial filter
  const getInitialDateRange = () => {
    if (initialFilter === "Week") return getWeek();
    if (initialFilter === "Month") return getMonth();
    if (initialFilter === "Today") return getToday();
    return getDefaultDateRange(); // fallback to current month
  };

  const [dateFilterType, setDateFilterType] = useState(initialFilter);
  const [pickerVisible, setPickerVisible] = useState(false);
  const [selectedRange, setSelectedRange] = useState(
    isRangePicker ? getInitialDateRange() : getToday()
  );
  const [selectedDate, setSelectedDate] = useState(new Date());
  const inputRef = useRef(null);

  // =========================
  // Dedicated Handlers
  // =========================

  const handleRangeSelect = (range) => {
    setSelectedRange(range);
  };

  const handleSingleSelect = (date) => {
    setSelectedDate(date);
  };

  const closePicker = () => {
    if (inputRef.current) {
      inputRef.current.value = "";
    }
    setPickerVisible(false);
  };

  const handleToday = () => {
    const value = getToday();
    if (isRangePicker) {
      setSelectedRange(value);
    } else {
      setSelectedDate(value);
    }
    setDateFilterType("Today");
    onChange("Today", value);
    closePicker();
  };

  const handleWeek = () => {
    const value = getWeek();
    setSelectedRange(value);
    setDateFilterType("Week");
    onChange("Week", value);
    closePicker();
  };

  const handleMonth = () => {
    const value = getMonth();
    setSelectedRange(value);
    setDateFilterType("Month");
    onChange("Month", value);
    closePicker();
  };

  const handleCustom = () => {
    setDateFilterType("Custom");
  };

  const applyDateRange = () => {
    if (!inputRef.current) return;

    const formattedValue = isRangePicker
      ? `${format(selectedRange.startDate, dateFormat)} - ${format(
          selectedRange.endDate,
          dateFormat
        )}`
      : format(selectedDate, dateFormat);

    inputRef.current.value = formattedValue;

    setPickerVisible(false);

    onChange(
      "Custom",
      isRangePicker ? selectedRange : selectedDate
    );
  };

  // =========================
  // UI
  // =========================

  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: "10px",
        position: "relative",
      }}
    >
      <Select
        value={dateFilterType}
        onChange={(e) => {
          const value = e.target.value;

          if (value === "Today") handleToday();
          else if (value === "Week") handleWeek();
          else if (value === "Month") handleMonth();
          else handleCustom();
        }}
        inputProps={{ "aria-label": "Date Filter" }}
        style={{
          width: "180px",
          height: "40px",
          backgroundColor: "white",
        }}
      >
        <MenuItem value="Today">Today</MenuItem>
        <MenuItem value="Week">Current Week</MenuItem>
        <MenuItem value="Month">Current Month</MenuItem>
        <MenuItem value="Custom">Custom Range</MenuItem>
      </Select>

      {dateFilterType === "Custom" && (
        <div className="datepicker">
          <div className="date-picker-icon">
            <input
              ref={inputRef}
              type="text"
              placeholder={placeholder}
              onClick={() => setPickerVisible(true)}
              readOnly
              className="date-range-input calenderIcon"
            />
          </div>

          {pickerVisible && (
            <Box
              className="date-range-container"
              sx={{
                boxShadow: 1,
                left: "2px",
                position: "absolute",
                top: "45px",
                zIndex: 1000,
                backgroundColor: "white",
              }}
            >
              {isRangePicker ? (
                <CustomDateRangePicker
                  onChange={handleRangeSelect}
                  onApply={applyDateRange}
                  onClose={() => setPickerVisible(false)}
                  selDate={selectedRange}
                />
              ) : (
                <SingleDatePicker
                  onChange={handleSingleSelect}
                  onApply={applyDateRange}
                  onClose={() => setPickerVisible(false)}
                  selDate={selectedDate}
                  dateFormat={dateFormat}
                />
              )}
            </Box>
          )}
        </div>
      )}
    </div>
  );
};


DateFilterDropdown.propTypes = {
  onChange: PropTypes.func.isRequired,
  initialFilter: PropTypes.oneOf(["Today", "Week", "Month", "Custom"]),
  isRangePicker: PropTypes.bool,
  dateFormat: PropTypes.string,
  placeholder: PropTypes.string,
};

export default DateFilterDropdown;