import React, { useState, useEffect } from "react";
import { Dropdown } from "react-bootstrap";
import { DropdownButton } from "react-bootstrap";
import styles from "@/styles/Component/Dashboard/LeadsStatement.module.scss";
import moment from "moment";
import { useApp } from "@/components/App";

interface QuarterlyDateRangePickerProps {
  currentYear: string;
  setCurrentYear: (year: string) => void;
  setSelectedStartDate: (date: string) => void;
  setSelectedEndDate: (date: string) => void;
}

interface QuarterOption {
  value: string;
  label: string;
  startDate: string;
  endDate: string;
}

const QuarterlyDateRangePicker: React.FC<QuarterlyDateRangePickerProps> = ({
  setSelectedStartDate,
  setSelectedEndDate
}) => {
  const { userDetail } = useApp();
  const [quarterOptions, setQuarterOptions] = useState<QuarterOption[]>([]);
  const [fromValue, setFromValue] = useState<string>("");
  const [toValue, setToValue] = useState<string>("");

  useEffect(() => {
    if (userDetail?.created_at) {
     const startYear = moment(userDetail.created_at).year();
      const currentYear = moment().year();
      const currentMonth = moment().month(); // 0-based (0 = Jan)

      // Define max quarter number (1 to 4) we should include based on current month
      let maxQuarter = 4;
      if (currentMonth <= 2) {
        maxQuarter = 1; // Jan-Mar
      } else if (currentMonth <= 5) {
        maxQuarter = 2; // Apr-Jun
      } else if (currentMonth <= 8) {
        maxQuarter = 3; // Jul-Sep
      } else {
        maxQuarter = 4; // Oct-Dec
      }

      // YOUR custom 'from' date
      const fromDate = moment('2024-05-01', 'YYYY-MM-DD'); // Example

      const yearRange = Array.from(
        { length: currentYear - startYear + 1 },
        (_, i) => (startYear + i).toString()
      );

      const options: QuarterOption[] = [];
      yearRange.forEach(year => {
        ['Q1', 'Q2', 'Q3', 'Q4'].forEach(quarter => {
          const quarterNumber = parseInt(quarter.replace('Q', ''));
          if (parseInt(year) === currentYear && quarterNumber > maxQuarter) {
            // Skip future quarters in the current year
            return;
          }

          const quarterToMonth = {
            'Q1': '01',
            'Q2': '04',
            'Q3': '07',
            'Q4': '10'
          };
          const month = quarterToMonth[quarter as keyof typeof quarterToMonth];
          const startDateMoment = moment(`${year}-${month}-01`, 'YYYY-MM-DD');
          const endDateMoment = startDateMoment.clone().add(2, 'months').endOf('month');

          // ✅ New: skip this quarter if it ends before the 'from' date
          if (endDateMoment.isBefore(fromDate, 'day')) {
            return;
          }

          options.push({
            value: `${year}-${quarter}`,
            label: `${year} ${quarter}`,
            startDate: startDateMoment.format('DD/MM/YYYY'),
            endDate: endDateMoment.format('DD/MM/YYYY')
          });
        });
      });



      setQuarterOptions(options);
      
      // Set initial values
      const initialYear = startYear.toString();
      setFromValue(`${initialYear}-Q1`);
      setToValue(`${initialYear}-Q1`);
      const initialOption = options.find(opt => opt.value === `${initialYear}-Q1`);
      if (initialOption) {
        setSelectedStartDate(initialOption.startDate);
        setSelectedEndDate(initialOption.endDate);
      }
    }
  }, [userDetail?.created_at]);

  const handleDateRangeChange = (option: QuarterOption, isFrom: boolean) => {
    // @typescript-eslint/no-unused-vars
    // const [year, quarter] = option.value.split('-');

    
    if (isFrom) {
      setFromValue(option.value);
      setSelectedStartDate(option.startDate);
      // If 'To' is before 'From' or empty, set 'To' to 'From'
      if (!toValue || quarterOptions.findIndex(opt => opt.value === toValue) < quarterOptions.findIndex(opt => opt.value === option.value)) {
        setToValue(option.value);
        setSelectedEndDate(option.endDate);
      }
    } else {
      setToValue(option.value);
      setSelectedEndDate(option.endDate);
      // If 'From' is after 'To' or empty, set 'From' to 'To'
      if (!fromValue || quarterOptions.findIndex(opt => opt.value === fromValue) > quarterOptions.findIndex(opt => opt.value === option.value)) {
        setFromValue(option.value);
        setSelectedStartDate(option.startDate);
      }
    }
  };

  if (!userDetail?.created_at) return null;

  return (
    <div className="d-flex align-items-center">
      <label>From:</label>
      <DropdownButton
        id="quarterly-dropdown-from"
        title={quarterOptions.find(opt => opt.value === fromValue)?.label || "Select"}
        variant="outline-secondary"
        className={`${styles.FIlterCustomDropdown} customDropdown mx-1`}
      >
        <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
          {quarterOptions.map((option) => (
            <Dropdown.Item
              key={option.value}
              onClick={() => handleDateRangeChange(option, true)}
            >
              {option.label}
            </Dropdown.Item>
          ))}
        </div>
      </DropdownButton>

      <label>To:</label>
      <DropdownButton
        id="quarterly-dropdown-to"
        title={quarterOptions.find(opt => opt.value === toValue)?.label || "Select"}
        variant="outline-secondary"
        className={`${styles.FIlterCustomDropdown} customDropdown mx-1`}
      >
        <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
          {quarterOptions
            .map((option) => (
              <Dropdown.Item
                key={option.value}
                onClick={() => handleDateRangeChange(option, false)}
              >
                {option.label}
              </Dropdown.Item>
            ))}
        </div>
      </DropdownButton>
    </div>
  );
};

export default QuarterlyDateRangePicker; 