import React, { useEffect, useState, useMemo } from "react";
import { Dropdown, DropdownButton } from "react-bootstrap";
import styles from "@/styles/Component/Dashboard/LeadsStatement.module.scss";
import moment from "moment";
import { useApp } from "@/components/App";
import { getStartInitialDate } from "@/utils/helpers";

// Interface with optional setters
interface MonthlyDateRangePickerProps {
  setSelectedStartDate?: (date: string) => void;
  setSelectedEndDate?: (date: string) => void;
}

// Helper function to generate months between two dates
function getMonthRange(start: moment.Moment, end: moment.Moment) {
  const months = [];
  const current = start.clone().startOf("month"); // Use clone to avoid mutating the original

  while (current.isSameOrBefore(end, "month")) {
    months.push({
      value: current.format("YYYY-MM"),
      label: current.format("MMMM YYYY")
    });
    current.add(1, "month");
  }

  return months;
}

const MonthlyDateRangePicker: React.FC<MonthlyDateRangePickerProps> = ({
  setSelectedStartDate,
  setSelectedEndDate
}) => {
  const { userDetail } = useApp();
  const createdAt = userDetail?.created_at;

  // Provide a fallback for hooks
  const startDateString = createdAt ? getStartInitialDate(moment(createdAt)) : "";
  const startMoment = createdAt ? moment(startDateString, "DD/MM/YYYY") : moment();

  // Generate month options using the correctly parsed startMoment
  const monthOptions = useMemo(
    () => (createdAt ? getMonthRange(startMoment, moment()) : []),
    [createdAt, startMoment]
  );

  // Initialize state with fallback in case monthOptions is empty
  const [fromMonth, setFromMonth] = useState(monthOptions[0]?.value || "");
  const [toMonth, setToMonth] = useState(
    monthOptions[monthOptions.length - 1]?.value || ""
  );

  // Set initial values when monthOptions is populated
  useEffect(() => {
    if (monthOptions.length > 0 && !fromMonth && !toMonth) {
      setFromMonth(monthOptions[0].value);
      setToMonth(monthOptions[monthOptions.length - 1].value);
    }
  }, [monthOptions, fromMonth, toMonth]);

  useEffect(() => {
    if (!fromMonth || !toMonth) return;

    // Parse fromMonth and toMonth with explicit format since they are in "YYYY-MM"
    const fromMoment = moment(fromMonth + "-01", "YYYY-MM-DD");
    const toMoment = moment(toMonth + "-01", "YYYY-MM-DD");

    if (fromMoment.isAfter(toMoment)) {
      // Auto-correct 'to' month if it's before 'from'
      setToMonth(fromMonth);
      return;
    }

    const startDate = fromMoment.startOf("month").format("DD/MM/YYYY");
    const endDate = toMoment.endOf("month").format("DD/MM/YYYY");

    // Call setters if provided
    setSelectedStartDate?.(startDate);
    setSelectedEndDate?.(endDate);
  }, [fromMonth, toMonth, setSelectedStartDate, setSelectedEndDate]);

  if (!createdAt) {
    return <div>Loading...</div>;
  }

  return (
    <div className="d-flex align-items-center gap-1 mx-3">
      <label>From:</label>
      <DropdownButton
        id="from-month-dropdown"
        title={monthOptions.find(m => m.value === fromMonth)?.label || "Select"}
        variant="outline-secondary"
        className={`${styles.FIlterCustomDropdown} customDropdown`}
      >
        <div style={{ maxHeight: "200px", overflowY: "auto" }}>
          {monthOptions.map(month => (
            <Dropdown.Item
              key={month.value}
              onClick={() => {
                setFromMonth(month.value);
                if (
                  moment(month.value + "-01", "YYYY-MM-DD").isAfter(
                    moment(toMonth + "-01", "YYYY-MM-DD")
                  )
                ) {
                  setToMonth(month.value);
                }
              }}
            >
              {month.label}
            </Dropdown.Item>
          ))}
        </div>
      </DropdownButton>

      <label>To:</label>
      <DropdownButton
        id="to-month-dropdown"
        title={monthOptions.find(m => m.value === toMonth)?.label || "Select"}
        variant="outline-secondary"
        className={`${styles.FIlterCustomDropdown} customDropdown`}
      >
        <div style={{ maxHeight: "200px", overflowY: "auto" }}>
          {monthOptions.map(month => (
            <Dropdown.Item
              key={month.value}
              onClick={() => {
                setToMonth(month.value);
                if (
                  moment(month.value + "-01", "YYYY-MM-DD").isBefore(
                    moment(fromMonth + "-01", "YYYY-MM-DD")
                  )
                ) {
                  setFromMonth(month.value);
                }
              }}
            >
              {month.label}
            </Dropdown.Item>
          ))}
        </div>
      </DropdownButton>
    </div>
  );
};

export default MonthlyDateRangePicker;
