"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHXDatePicker = PHXDatePicker;
const tslib_1 = require("tslib");
const solid_1 = require("@heroicons/react/20/solid");
const react_1 = tslib_1.__importStar(require("react"));
const Calendar_1 = tslib_1.__importDefault(require("./components/Calendar"));
const ErrorMessage_1 = tslib_1.__importDefault(require("../../commons/ErrorMessage"));
function classNames(...classes) {
    return classes.filter(Boolean).join(' ');
}
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 = (0, react_1.useRef)(null);
    const calendarRef = (0, react_1.useRef)(null);
    const [isCalendarVisible, setIsCalendarVisible] = (0, react_1.useState)(false);
    const [inputValue, setInputValue] = (0, react_1.useState)('');
    const [inputChange, setInputChange] = (0, react_1.useState)('');
    const [isOnChange, setIsOnChange] = (0, react_1.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) });
        }
    };
    (0, react_1.useEffect)(() => {
        if (defaultValue) {
            // @ts-ignore
            setInputValue(defaultValue);
        }
    }, [defaultValue]);
    (0, react_1.useEffect)(() => {
        if (clearValue) {
            setInputValue('');
        }
    }, [clearValue]);
    (0, react_1.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_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: className },
            label && react_1.default.createElement("label", { className: 'mb-1 block text-xs font-normal text-gray-700' }, label),
            react_1.default.createElement("div", { className: 'relative' },
                react_1.default.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_1.default.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_1.default.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_1.default.createElement("div", { className: 'mt-1 text-xs text-gray-500' }, helpText) : null,
                error && errorType ? react_1.default.createElement(ErrorMessage_1.default, { message: message(errorType) }) : null,
                react_1.default.createElement("div", { className: 'absolute left-3 top-2' },
                    react_1.default.createElement(solid_1.CalendarDaysIcon, { className: 'h-4 w-4 text-gray-500' })),
                react_1.default.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_1.default.createElement(Calendar_1.default, { defaultDate: defaultValue, disabledDate: disabledDate, endDisabled: endDisabled, inputValue: inputChange, max: max, min: min, onChangeDate: (val) => handleSelectDate(val), startDisabled: startDisabled, setIsCalendarVisible: setIsCalendarVisible }))))));
}
//# sourceMappingURL=DatePicker.js.map