import React, { useState, useRef, useEffect } from 'react';
import { Calendar } 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 moment from 'moment';
import "../pages/TopUsersScreen.css"

function SingleDatePicker({ onChange, value, onApply, onClose }) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedDate, setSelectedDate] = useState(value || new Date());
  const [tempDate, setTempDate] = useState(value || new Date());
  const containerRef = useRef(null);

  // Get today's date
  const today = new Date();
  today.setHours(23, 59, 59, 999);

  // First day of previous month
  const firstDayOfPreviousMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);

  // Update internal state when value prop changes
  useEffect(() => {
    if (value) {
      setSelectedDate(value);
      setTempDate(value);
    }
  }, [value]);

  // Close calendar when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleInputClick = () => {
    setIsOpen(!isOpen);
  };

  const handleSelect = (date) => {
    setTempDate(date);
    onChange(date);
  };

  const handleApply = () => {
    setSelectedDate(tempDate);
    const formattedDate = new Date(tempDate);
    formattedDate.setHours(0, 0, 0, 0);
    const isoString = new Date(formattedDate.getTime() - formattedDate.getTimezoneOffset() * 60000).toISOString();
    onChange(isoString);
    if (onApply) {
      onApply(isoString);
    }
    setIsOpen(false);
  };

  const handleClose = () => {
    setTempDate(selectedDate); // Reset to previously selected date
    setIsOpen(false);
    if (onClose) {
      onClose();
    }
  };

  const handleClear = () => {
    const today = new Date();
    setSelectedDate(today);
    setTempDate(today);
    const formattedDate = new Date(today);
    formattedDate.setHours(0, 0, 0, 0);
    const isoString = new Date(formattedDate.getTime() - formattedDate.getTimezoneOffset() * 60000).toISOString();
    onChange(isoString);
    setIsOpen(false);
  };

  return (
    <div ref={containerRef} style={{ position: 'relative' }}>
      <div style={{ position: 'relative', display: 'inline-block' }}>
        <input
          type="text"
          value={moment(selectedDate).format("YYYY-MM-DD")}
          onClick={handleInputClick}
          readOnly
          placeholder="Select date"
          style={{
            padding: '8px 35px 8px 12px',
            border: '1px solid #ccc',
            borderRadius: '4px',
            cursor: 'pointer',
            backgroundColor: '#fff',
            minWidth: '150px'
          }}
        />
        <svg
          onClick={handleInputClick}
          style={{
            position: 'absolute',
            right: '8px',
            top: '50%',
            transform: 'translateY(-50%)',
            width: '16px',
            height: '16px',
            cursor: 'pointer',
            fill: '#666'
          }}
          viewBox="0 0 24 24"
        >
          <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.89-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.11-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
        </svg>
      </div>
      
      {isOpen && (
        <div style={{
          position: 'absolute',
          top: '100%',
          left: 0,
          zIndex: 1000,
          backgroundColor: '#fff',
          border: '1px solid #ccc',
          borderRadius: '4px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
          marginTop: '4px'
        }}>
          <div style={{ backgroundColor: '#fff', borderRadius: '4px' }}>
            <Calendar
              date={tempDate}
              onChange={handleSelect}
              minDate={firstDayOfPreviousMonth}
              maxDate={today}
            />
          </div>
          <div className='action-buttons-date-picker' style={{ padding: '10px', borderTop: '1px solid #eee', backgroundColor: '#fff' }}>
            <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
              <button className='button' onClick={handleApply}>Apply</button>
              <button className='btn2' onClick={handleClear}>Clear</button>
              <button className='btn2' onClick={handleClose}>Close</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

SingleDatePicker.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]),
  onApply: PropTypes.func,
  onClose: PropTypes.func,
};

export default SingleDatePicker;

