import ReactDatePicker from "react-datepicker";
import FieldsActions from '../actions/FieldsActions';
import { useDispatch } from "react-redux";
import {format} from 'date-fns';
const {newSelectValue} = FieldsActions

const DatePicker = ({temporaryID, propertyName, getValue, labels = {}}) => {
    let startDate;

    if (getValue()) {
        let dateParts = getValue().split('-');

        // Please note that the month is 0-indexed
        startDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
    } else {
        startDate = new Date();
    }
    const dispatch = useDispatch();

    return (
        <div className="flex flex-row items-center w-full">
            {labels?.left? (
                <span className="mr-1">{labels?.left}</span>
            ) : ''}
                <ReactDatePicker 
                    selected={startDate} 
                    onChange={(date) =>  {
                        dispatch(newSelectValue(
                           format(date, 'yyyy-MM-dd'), temporaryID, propertyName
                       ))
                    }} 
                    dateFormat="MMM d, yyyy"
                    locale={navigator.language}
                    className="relative w-32 space-x-1 flex flex-row justify-between items-center px-3 h-9 text-left rounded-4 border-px border-gray-200 text-gray-650 focus:border-blue-normal focus:outline-none shadow-input cursor-default hover:cursor-pointer text-base select-none"
                />
            {labels?.right? (
                <span className="ml-2">{labels?.right}</span>
            ) : ''}
        </div>
    );
}

export default DatePicker;