import { useEffect, useRef } from 'react';
import { Box, FormControl, FormLabel, Input } from '@chakra-ui/react';

function DateRangePicker({ selectedDates, onDateChange }) {
  const startDateRef = useRef();
  const endDateRef = useRef();

  const currentDate = new Date().toISOString().split('T')[0];

  useEffect(() => {
    if (selectedDates?.startDate) {
      startDateRef.current.value = selectedDates.startDate;
    }

    if (selectedDates?.endDate) {
      endDateRef.current.value = selectedDates.endDate;
    }
  }, [selectedDates]);

  const handleStartDateChange = () => {
    if (onDateChange) {
      onDateChange({ startDate: startDateRef.current.value, endDate: endDateRef.current.value });
    }
  };

  const handleEndDateChange = () => {
    if (onDateChange) {
      onDateChange({ startDate: startDateRef.current.value, endDate: endDateRef.current.value });
    }
  };

  return (
    <Box>
      <FormControl>
        <FormLabel>Start Date</FormLabel>
        <Input type="date" defaultValue={currentDate} ref={startDateRef} onChange={handleStartDateChange} />
      </FormControl>
      <FormControl mt={3}>
        <FormLabel>End Date</FormLabel>
        <Input type="date" defaultValue={currentDate} ref={endDateRef} onChange={handleEndDateChange} />
      </FormControl>
    </Box>
  );
}

export default DateRangePicker;
