import React, { useState, useEffect, useRef } from 'react';
import { DateRange } from 'react-date-range';
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';
import PropTypes from 'prop-types';
import { formatDate, getDefaultDateRange } from '../constants/dateUtils.js';
import "../pages/TopUsersScreen.css";
import { toast } from 'react-toastify';


function CustomDateRangePicker({ onChange, onApply, onClose, selDate, disableDefaultRange = false }) {
  const today = new Date(new Date().setHours(23, 59, 59, 999));
  const firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);


  const [selectionRange, setSelectionRange] = useState(() => {
    if (selDate?.startDate && selDate?.endDate) {
      return {
        startDate: new Date(selDate.startDate),
        endDate: new Date(selDate.endDate),
        key: 'selection'
      };
    }


    if (disableDefaultRange) {
      return { startDate: today, endDate: today, key: 'selection' };
    }

    return { ...getDefaultDateRange(), key: 'selection' };
  });

  const [isApplyDisabled, setIsApplyDisabled] = useState(false);
  const toastShownRef = useRef(false);


  const validateDateRange = (startDate, endDate) => {
    if (!startDate || !endDate) return;

    const oneDay = 1000 * 60 * 60 * 24;
    const diffInTime = endDate.getTime() - startDate.getTime();
    const diffInDays = Math.round(diffInTime / oneDay);

    if (diffInDays > 30) {
      setIsApplyDisabled(true);
      if (!toastShownRef.current) {
        toast.error("You are not allowed to select more than 30 days");
        toastShownRef.current = true;
      }
    } else {
      setIsApplyDisabled(false);
      toastShownRef.current = false;
    }
  };


  useEffect(() => {
    if (!disableDefaultRange && (!selDate?.startDate || !selDate?.endDate)) {
      const { startDate, endDate } = getDefaultDateRange();
      onChange({
        startDate: formatDate(startDate),
        endDate: formatDate(endDate)
      });
    }
  }, [disableDefaultRange]);


  useEffect(() => {
    if (selectionRange.startDate && selectionRange.endDate) {
      validateDateRange(selectionRange.startDate, selectionRange.endDate);
    }
  }, [selectionRange]);

  const handleSelect = (ranges) => {
    const startDate = new Date(ranges.selection.startDate);
    const endDate = new Date(ranges.selection.endDate);
    startDate.setHours(0, 0, 0, 0);
    endDate.setHours(23, 59, 59, 999);

    setSelectionRange({
      startDate,
      endDate,
      key: 'selection',
    });

    const formattedStartDate = new Date(startDate.getTime() - startDate.getTimezoneOffset() * 60000)
      .toISOString()
      .split('T')[0];
    const formattedEndDate = new Date(endDate.getTime() - endDate.getTimezoneOffset() * 60000)
      .toISOString()
      .split('T')[0];

    onChange({
      startDate: formattedStartDate,
      endDate: formattedEndDate,
    });
  };

  const handleClear = () => {
    const resetSelection = {
      startDate: today,
      endDate: today,
      key: 'selection',
    };
    setSelectionRange(resetSelection);
    onChange({ startDate: resetSelection.startDate, endDate: resetSelection.endDate });
  };

  return (
    <div>
      <DateRange
        data-testid="date-range-picker"
        ranges={[selectionRange]}
        onChange={handleSelect}
        moveRangeOnFirstSelection={false}
        maxDate={today}
        minDate={firstDayOfLastMonth}
      />
      <div className='action-buttons-date-range-picker' data-testid="date-picker" >
        <div>
          <button
            className={`button ${isApplyDisabled ? 'disabled-button' : ''}`}
            onClick={() => onApply({
              startDate: selectionRange.startDate,
              endDate: selectionRange.endDate
            })}
            data-testid="date-range-picker"
            disabled={isApplyDisabled}
          >
            Apply
          </button>
          <button className='btn2' data-testid="search-clear-button" onClick={handleClear}>Clear</button>
          <button
            className='btn2'
            data-testid="close-date"
            onClick={() => {
              onClose();
              if (selectionRange.startDate && selectionRange.endDate) {
                validateDateRange(selectionRange.startDate, selectionRange.endDate);
              }
            }}
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

CustomDateRangePicker.propTypes = {
  onChange: PropTypes.func.isRequired,
  onApply: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
  selDate: PropTypes.object,
  disableDefaultRange: PropTypes.bool
};

export default CustomDateRangePicker;
