// import React, { useState } from 'react';
// import { DatePicker, Form, Select, Typography } from 'antd';
// import { Dayjs } from 'dayjs';
// import dayjs from 'dayjs';
// import moment from 'moment';

// const { RangePicker } = DatePicker;
// const { Title } = Typography;

// interface DateRangeFilterProps {
//   onDateChange: (range: string | null) => void;
//   label?: string;
//   initialRange?: [string, string] | null;
// }
// type QuickRange = {
//   label: string;
//   days?: number;
//   start?: string;
//   end?: string;
// };

// const DateRangeFilter: React.FC<DateRangeFilterProps> = ({ onDateChange, label = '', initialRange }) => {
//   const [error, setError] = useState<string | null>(null);
//   const [selectedDates, setSelectedDates] = useState<[Dayjs | null, Dayjs | null] | null>(
//     initialRange ? [dayjs(initialRange[0]), dayjs(initialRange[1])] : null
//   );
//   const [pickerOpen, setPickerOpen] = useState(false);
//   const [selectedQuickRange, setSelectedQuickRange] = useState<string | undefined>();

//     const getFinancialYears = (): QuickRange[] => {
//     const today = dayjs();

//     // April = month 3 (0-indexed)
//     const currentFYStartYear =
//       today.month() >= 3 ? today.year() : today.year() - 1;

//     return [
//       {
//         label: `FY ${currentFYStartYear - 1}-${currentFYStartYear}`,
//         start: `${currentFYStartYear - 1}-04-01`,
//         end: `${currentFYStartYear}-03-31`,
//       },
//       {
//         label: `FY ${currentFYStartYear}-${currentFYStartYear + 1}`,
//         start: `${currentFYStartYear}-04-01`,
//         end: `${currentFYStartYear + 1}-03-31`,
//       },
//     ];
//   };

//   const handleChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
//     setSelectedDates(dates);
//     setSelectedQuickRange(undefined);
//     if (dates && dates[0] && dates[1]) {
//       setError(null);
//       onDateChange(`'${dates[0].format('YYYY-MM-DD')} 00:00:00' AND '${dates[1].format('YYYY-MM-DD')} 23:59:59'`);
//     } else {
//       setError(null);
//       onDateChange(null);
//     }
//     // setPickerOpen(false); // Close popup after selection
//   };

//   const disabledDate = (current: any): boolean => {
//     // Specify the types
//     return current.isAfter(moment().endOf('day'));
//   };

//   const quickRanges: QuickRange[] = [
//     { label: 'Last 7 Days', days: 7 },
//     { label: 'Last 15 Days', days: 15 },
//     { label: 'Last 1 Month', days: 30 },
//     ...getFinancialYears(),
//   ];

//   const handleQuickSelection = (label?: string) => {
//     if (!label) {
//       setSelectedQuickRange(undefined);
//       setSelectedDates(null);
//       setError(null);
//       onDateChange(null);
//       return;
//     }

//     setSelectedQuickRange(label);

//     const range = quickRanges.find((item) => item.label === label);

//     if (!range) return;

//     let startDate: Dayjs;
//     let endDate: Dayjs;

//     if (range.days) {
//       endDate = dayjs();
//       startDate = dayjs().subtract(range.days, 'day');
//     } else {
//       startDate = dayjs(range.start);
//       endDate = dayjs(range.end);
//     }

//     setSelectedDates([startDate, endDate]);
//     setError(null);

//     onDateChange(
//       `'${startDate.format('YYYY-MM-DD')} 00:00:00' AND '${endDate.format('YYYY-MM-DD')} 23:59:59'`
//     );

//     // setPickerOpen(false);
//   };

//   const extraFooter = (
//     <div
//     onMouseDown={(e) => {
//       e.preventDefault();
//       e.stopPropagation();
//     }}
//       style={{
//         display: 'flex',
//         alignItems: 'center',
//         justifyContent: 'space-between',
//         gap: 12,
//         padding: '8px 0',
//       }}
//     >
//         <Title level={5} style={{ margin: 0 }}>
//          Quick Date Range Pick
//       </Title>

//       <Select
//         allowClear
//         placeholder="Select"
//         style={{ width: 220 }}
//         value={selectedQuickRange}
//         options={quickRanges.map((range) => ({
//           label: range.label,
//           value: range.label,
//         }))}
//         onChange={(value) => handleQuickSelection(value)}
//         onClear={() => handleQuickSelection(undefined)}
//       />
//     </div>
//   );
//   return (
//     <Form.Item label={label} validateStatus={error ? 'error' : ''} help={error}>
//       <RangePicker
//         onChange={handleChange}
//         value={selectedDates}
//         renderExtraFooter={() => extraFooter}
//         open={pickerOpen}
//         onOpenChange={(open) => setPickerOpen(open)}
//         disabledDate={disabledDate}
//       />
//     </Form.Item>
//   );
// };

// export default DateRangeFilter;

import React, { useState } from 'react';
import { DatePicker, Form, Button } from 'antd';
import { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import moment from 'moment';

const { RangePicker } = DatePicker;

interface DateRangeFilterProps {
  onDateChange: (range: string | null) => void;
  label?: string;
  initialRange?: [string, string] | null;
}

const DateRangeFilter: React.FC<DateRangeFilterProps> = ({ onDateChange, label = '', initialRange }) => {
  const [error, setError] = useState<string | null>(null);
  const [selectedDates, setSelectedDates] = useState<[Dayjs | null, Dayjs | null] | null>(
    initialRange ? [dayjs(initialRange[0]), dayjs(initialRange[1])] : null
  );
  const [pickerOpen, setPickerOpen] = useState(false);

  const handleChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
    setSelectedDates(dates);
    if (dates && dates[0] && dates[1]) {
      setError(null);
      onDateChange(`'${dates[0].format('YYYY-MM-DD')} 00:00:00' AND '${dates[1].format('YYYY-MM-DD')} 23:59:59'`);
    } else {
      setError(null);
      onDateChange(null);
    }
    setPickerOpen(false); // Close popup after selection
  };

  const disabledDate = (current: any): boolean => {
    // Specify the types
    return current.isAfter(moment().endOf('day'));
  };

      const getFinancialYears = () => {
      const today = dayjs();

      // April = month 3 (0-indexed)
      const currentFYStartYear =  today.month() >= 3 ? today.year() : today.year() - 1;

      return [
        {
          label: `FY ${currentFYStartYear - 1}-${currentFYStartYear}`,
          start: `${currentFYStartYear - 1}-04-01`,
          end: `${currentFYStartYear}-03-31`,
        },
        {
          label: `FY ${currentFYStartYear}-${currentFYStartYear + 1}`,
          start: `${currentFYStartYear}-04-01`,
          end: `${currentFYStartYear + 1}-03-31`,
        },
      ];
    };

  const quickRanges = [
    { label: 'Last 7 Days', days: 7 },
    { label: 'Last 15 Days', days: 15 },
    { label: 'Last 1 Month', days: 30 },
     ...getFinancialYears(),
  ];

  const handleQuickSelection = (range: any) => {
    let startDate: Dayjs;
    let endDate: Dayjs;

    if (range.days) {
      endDate = dayjs();
      startDate = dayjs().subtract(range.days, 'day');
    } else {
      startDate = dayjs(range.start);
      endDate = dayjs(range.end);
    }

    setSelectedDates([startDate, endDate]);
    setError(null);

    onDateChange(
      `'${startDate.format('YYYY-MM-DD')} 00:00:00' AND '${endDate.format('YYYY-MM-DD')} 23:59:59'`
    );

    setPickerOpen(false);
  };

  const extraFooter = (
    <div
      style={{ display: 'flex', gap: '8px', padding: '8px 0' }}
    >
      {quickRanges.map((range) => (
        <Button
          key={range.label}
          type="primary"
          style={{
            flex: 1, borderRadius: '4px', padding: '0 8px', fontSize: '13px', fontWeight: 500,
          }}
          onClick={() => handleQuickSelection(range)}
        >
          {range.label}
        </Button>
      ))}
    </div>
  );
  return (
    <Form.Item label={label} validateStatus={error ? 'error' : ''} help={error}>
      <RangePicker
        onChange={handleChange}
        value={selectedDates}
        renderExtraFooter={() => extraFooter}
        open={pickerOpen}
        onOpenChange={(open) => setPickerOpen(open)}
        disabledDate={disabledDate}
      />
    </Form.Item>
  );
};

export default DateRangeFilter;
