import { CalendarDaysIcon } from '@heroicons/react/20/solid';
import React, { useEffect, useRef, useState } from 'react';
import Calendar from './components/Calendar';
import ErrorMessage from '../../commons/ErrorMessage';
function classNames(...classes) {
    return classes.filter(Boolean).join(' ');
}
export function PHXDatePicker({ className, defaultValue, disabled, disabledDate, endDisabled, error, errorType, id = 'date-picker', label, max, min, onChange, onChangeDate, origin = 'bottom-left', register, startDisabled, errorMessageCustom, placeholder, readOnly = false, helpText, clearValue = false, }) {
    const message = (type) => {
        let errorMessage = '';
        switch (type) {
            case 'required-field':
                errorMessage = 'Vui lòng nhập thông tin';
                break;
            case 'duplicate-field':
                errorMessage = 'Thông tin đã tồn tại';
                break;
            case 'custom-message':
                errorMessage = errorMessageCustom;
                break;
            default:
                break;
        }
        return errorMessage;
    };
    const inputRef = useRef(null);
    const calendarRef = useRef(null);
    const [isCalendarVisible, setIsCalendarVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const [inputChange, setInputChange] = useState('');
    const [isOnChange, setIsOnChange] = useState(false);
    const handleToggleCalendar = () => {
        setIsCalendarVisible(true);
    };
    const handleSelectDate = (selectedDate) => {
        const inputElement = document.getElementById(`${id}-after`);
        if (inputElement)
            inputElement.focus();
        if (onChangeDate) {
            onChangeDate(selectedDate);
        }
        setInputValue(selectedDate.format);
    };
    // const handleEnterInput = (event: any) => {
    //   // if (event.key === 'Enter') {
    //   const inputElement = document.getElementById(`${id}-after`)
    //   if (inputElement) inputElement.focus()
    //   setInputChange(event.target.value)
    //   // }
    // }
    const handleChangeInput = (event) => {
        setIsOnChange(true);
        setInputValue(event.target.value);
        setInputChange(event.target.value);
        if (onChange) {
            const dateArr = event.target.value.split('-');
            const year = dateArr[2];
            const month = dateArr[1];
            const day = dateArr[0];
            onChange({ format: event.target.value, date: new Date(year, month, day) });
        }
    };
    useEffect(() => {
        if (defaultValue) {
            // @ts-ignore
            setInputValue(defaultValue);
        }
    }, [defaultValue]);
    useEffect(() => {
        if (clearValue) {
            setInputValue('');
        }
    }, [clearValue]);
    useEffect(() => {
        const handleClickOutside = (event) => {
            var _a;
            if ((_a = calendarRef.current) === null || _a === void 0 ? void 0 : _a.contains(event.target))
                return;
            if (inputRef.current === event.target)
                return;
            setIsCalendarVisible(false);
            const inputElement = document.getElementById(`${id}-after`);
            if (inputElement && isOnChange) {
                inputElement.focus();
                setIsOnChange(false);
                inputElement.blur();
            }
        };
        window.addEventListener('mousedown', handleClickOutside, true);
        return () => {
            window.removeEventListener('mousedown', handleClickOutside, true);
        };
    }, [isOnChange]);
    const value = () => {
        switch (true) {
            case !!defaultValue && !!inputValue:
                return inputValue;
            case !!defaultValue && !inputValue:
                return defaultValue;
            default:
                return inputValue;
        }
    };
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: className },
            label && React.createElement("label", { className: 'mb-1 block text-xs font-normal text-gray-700' }, label),
            React.createElement("div", { className: 'relative' },
                React.createElement("label", { ref: inputRef, className: `absolute top-0 h-[1.875rem] w-full rounded-lg py-4 ${disabled ? 'normal' : 'cursor-pointer'}`, htmlFor: id, onClick: handleToggleCalendar }),
                React.createElement("input", { readOnly: readOnly, className: classNames('block w-full rounded-lg border-[0.5px] border-gray-500 px-3 py-1.5 pl-9 text-xs font-normal shadow-sm hover:bg-gray-50 focus:border-gray-500 focus:bg-gray-50 focus:outline-none focus:outline-offset-1 focus:outline-indigo-500 focus:ring-transparent', error ? 'border-red-800 bg-red-50 hover:bg-red-50 focus:border-red-800 focus:bg-red-50' : '', disabled ? 'bg-neutral-200 hover:bg-neutral-200 border-neutral-200' : ''), disabled: disabled, id: id, onChange: handleChangeInput, onFocus: () => {
                        setIsCalendarVisible(true);
                    }, 
                    // onKeyDown={handleEnterInput}
                    tabIndex: -1, value: value(), placeholder: placeholder }),
                React.createElement("input", { className: 'rounded-lg focus:ring-transparent w-full', id: `${id}-after`, 
                    // readOnly
                    style: {
                        content: '',
                        position: 'absolute',
                        height: 0,
                        top: -0,
                        zIndex: -100,
                    }, ...register, onChange: handleChangeInput, value: value() }),
                helpText ? React.createElement("div", { className: 'mt-1 text-xs text-gray-500' }, helpText) : null,
                error && errorType ? React.createElement(ErrorMessage, { message: message(errorType) }) : null,
                React.createElement("div", { className: 'absolute left-3 top-2' },
                    React.createElement(CalendarDaysIcon, { className: 'h-4 w-4 text-gray-500' })),
                React.createElement("div", { ref: calendarRef, className: classNames('absolute z-50', origin === 'top-left' && '-top-60 left-0', origin === 'top-right' && '-top-60 right-0', origin === 'bottom-left' && 'left-0 top-10', origin === 'bottom-right' && 'right-0 top-10', isCalendarVisible && !disabled ? '' : 'hidden') },
                    React.createElement(Calendar, { defaultDate: defaultValue, disabledDate: disabledDate, endDisabled: endDisabled, inputValue: inputChange, max: max, min: min, onChangeDate: (val) => handleSelectDate(val), startDisabled: startDisabled, setIsCalendarVisible: setIsCalendarVisible }))))));
}
//# sourceMappingURL=DatePicker.js.map