import React, { useCallback, useEffect, useState } from 'react'; import type { ChangeEventHandler, Dispatch, MouseEventHandler, SetStateAction } from 'react'; import InputMask from 'react-input-mask'; import clsx from 'clsx'; import TextField from '@mui/material/TextField'; import IconButton from '@mui/material/IconButton'; import { ASSETS_URL } from '../../../../../consts/common'; import { CustomIcon } from '../../../../custom-icon'; import { autoInputDate, parserInputValueDate } from './helpers'; import { textToDateDMY } from '../helpers'; import createClasses from './styles'; const defaultValue = '__/__/____ - __/__/____'; export interface HeaderDatePickerProps { handleOpen: (newState?: boolean) => void | MouseEventHandler; handleClear: () => void; placeholder?: string; startDate?: Date | null; endDate?: Date | null; setStartDate: Dispatch>; setEndDate: Dispatch>; open: boolean; id: string; fieldFocus: boolean; toggleFieldFocus: (nextValue?: unknown) => void; } const HeaderDatePicker = (props: HeaderDatePickerProps) => { const { handleOpen, handleClear, placeholder = 'Pick a date', startDate = null, endDate = null, setStartDate, setEndDate, open, id, fieldFocus, toggleFieldFocus } = props; const styles = createClasses(); const [value, setValue] = useState(''); useEffect(() => { if (startDate) { setValue(textToDateDMY(startDate, endDate)); } else { setValue(''); } }, [startDate, endDate]); useEffect(() => { const inputDate = parserInputValueDate(value); if (inputDate) { setStartDate(inputDate.start); setEndDate(inputDate.end); } // eslint-disable-next-line }, [value]); const onChangeInput: ChangeEventHandler = e => { setValue(autoInputDate(value, e.target.value)); }; const handleClearInput: MouseEventHandler = useCallback(() => { setValue(''); handleClear(); }, [handleClear]); const handleFocus = useCallback(() => { toggleFieldFocus(true); handleOpen(false); }, [handleOpen, toggleFieldFocus]); const handleBlur = useCallback(() => { toggleFieldFocus(false); }, [toggleFieldFocus]); return ( {() => ( {value && value !== defaultValue && ( )} ) }} /> )} ); }; export default HeaderDatePicker;