"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "useDateTimePicker", {
    enumerable: true,
    get: function() {
        return useDateTimePicker;
    }
});
const _react = require("react");
const _datejs = require("../../../utils/datejs");
const _utils = require("../../Calendar/utils");
const _dateHelper = require("../../DatePicker/utils/dateHelper");
const _DateTimePickertokens = require("../DateTimePicker.tokens");
const _getMaskedValue = require("../utils/getMaskedValue");
const _utils1 = require("../utils");
const useDateTimePicker = ({ valueError, valueSuccess, valueEdited, type, lang = 'ru', disabled, readOnly, outerValue, defaultDate, maskWithFormat, dateFormat = 'DD.MM.YYYY', timeFormat = 'HH:mm:ss', dateTimeSeparator = ' ', inputRef, min, max, includeEdgeDates, dateOnTimeSelectOnly, preserveInvalidOnBlur, onChangeValue, onCommitDate, onBlur })=>{
    const errorClass = valueError ? _DateTimePickertokens.classes.error : undefined;
    const successClass = valueSuccess ? _DateTimePickertokens.classes.success : undefined;
    const editedClass = valueEdited ? _DateTimePickertokens.classes.edited : undefined;
    const dateFormatDelimiter = (0, _react.useMemo)(()=>(0, _dateHelper.getDateFormatDelimiter)(dateFormat), [
        dateFormat
    ]);
    const timeFormatDelimiter = (0, _react.useMemo)(()=>(0, _dateHelper.getDateFormatDelimiter)(timeFormat), [
        timeFormat
    ]);
    const delimiters = [
        dateFormatDelimiter,
        timeFormatDelimiter,
        dateTimeSeparator
    ];
    const format = dateFormat + dateTimeSeparator + timeFormat;
    const timeColumnsCount = timeFormat?.split(timeFormatDelimiter).length || 2;
    const [innerDate, setInnerDate] = (0, _react.useState)(defaultDate || '');
    const dateVisibleValue = outerValue ?? innerDate;
    const initialValues = (0, _utils1.getFormattedDateTime)({
        value: dateVisibleValue,
        lang,
        format,
        includeEdgeDates,
        min,
        max,
        dateFormat,
        timeFormat
    });
    const [correctDates, setCorrectDates] = (0, _react.useState)({
        input: initialValues.formattedDate,
        calendar: initialValues.dateValue,
        time: initialValues.timeValue
    });
    const calendarGridValue = initialValues.dateValue;
    const timeGridValue = initialValues.timeValue;
    _datejs.customDayjs.locale(lang);
    const timeVisibleValue = timeGridValue ? (0, _datejs.customDayjs)(timeGridValue).format(timeFormat) : '';
    const inputValue = initialValues.formattedDate;
    const getQuarterInfo = (originalDate)=>{
        if (type !== 'Quarters' || !originalDate) {
            return;
        }
        const endQuarter = new Date(originalDate);
        endQuarter.setMonth(originalDate.getMonth() + 3);
        endQuarter.setDate(0);
        _datejs.customDayjs.locale(lang);
        const quarterIndex = (0, _datejs.customDayjs)(originalDate).quarter() - 1;
        return {
            name: _utils.QUARTER_NAMES[quarterIndex],
            fullValue: [
                originalDate,
                endQuarter
            ]
        };
    };
    const isDateEqualEdge = (dateEdge)=>{
        if (!dateEdge || !correctDates.calendar) {
            return false;
        }
        const normalizedEdgeDate = (0, _datejs.customDayjs)(dateEdge).startOf('day');
        const normalizedCurrentDate = (0, _datejs.customDayjs)(correctDates.calendar).startOf('day');
        return normalizedCurrentDate.isSame(normalizedEdgeDate);
    };
    const getFormattedCorrectInput = ({ originalDate, formattedDate, dateValue, timeValue })=>{
        if (originalDate || formattedDate === '') {
            return {
                input: formattedDate
            };
        }
        if (dateValue && timeValue) {
            return {
                input: formattedDate
            };
        }
        if (dateValue && !timeValue) {
            return {
                input: formattedDate.slice(0, dateFormat?.length)
            };
        }
        return {
            input: ''
        };
    };
    const handleChangeValue = (event)=>{
        if (disabled || readOnly) {
            return;
        }
        const { value, selectionStart } = event.target;
        const { formattedValue, selectionStart: newSelectionStart } = maskWithFormat ? (0, _getMaskedValue.getMaskedValue)({
            value,
            format,
            delimiters,
            prevValue: inputValue,
            selectionStart
        }) : {
            formattedValue: value,
            selectionStart
        };
        const { formattedDate, isoDate, originalDate, dateValue, timeValue } = (0, _utils1.getFormattedDateTime)({
            value: formattedValue,
            lang,
            format,
            dateFormat,
            timeFormat,
            includeEdgeDates,
            min,
            max
        });
        const { input: inputCorrectValue } = getFormattedCorrectInput({
            originalDate,
            formattedDate,
            dateValue,
            timeValue
        });
        setCorrectDates((prevCorrectDates)=>({
                ...prevCorrectDates,
                input: inputCorrectValue,
                calendar: inputCorrectValue ? dateValue || prevCorrectDates.calendar : undefined,
                time: inputCorrectValue ? timeValue || prevCorrectDates.time : undefined
            }));
        setInnerDate(formattedDate);
        if (originalDate) {
            const quarterInfo = getQuarterInfo(originalDate);
            if (onCommitDate) {
                onCommitDate(formattedDate, {
                    quarterInfo,
                    originalDate,
                    isoDate
                });
            }
        }
        if (onChangeValue) {
            onChangeValue(event, formattedDate, {
                originalDate,
                isoDate
            });
        }
        requestAnimationFrame(()=>{
            if (inputRef.current) {
                inputRef.current.setSelectionRange(newSelectionStart, newSelectionStart);
            }
        });
    };
    const handleSearch = (date)=>{
        if (disabled || readOnly) {
            return;
        }
        if (!date) {
            if (onCommitDate) {
                onCommitDate('', {
                    quarterInfo: undefined,
                    originalDate: undefined,
                    isoDate: ''
                });
            }
            return;
        }
        const { formattedDate, isoDate, originalDate } = (0, _utils1.getFormattedDateTime)({
            value: date,
            lang,
            format,
            dateFormat,
            timeFormat,
            includeEdgeDates,
            min,
            max
        });
        const quarterInfo = getQuarterInfo(originalDate);
        if (onCommitDate) {
            onCommitDate(formattedDate, {
                quarterInfo,
                originalDate,
                isoDate
            });
        }
    };
    const handleCalendarPick = (date, quarterInfo)=>{
        if (disabled || readOnly) {
            return;
        }
        if (!date) {
            return;
        }
        _datejs.customDayjs.locale(lang);
        let rawDate = (0, _datejs.customDayjs)(date);
        if (correctDates.time) {
            const correctTimeDate = (0, _datejs.customDayjs)(correctDates.time);
            const correctHours = correctTimeDate.get('hours');
            const correctMinutes = correctTimeDate.get('minutes');
            const correctSeconds = correctTimeDate.get('seconds');
            rawDate = rawDate.set('hours', correctHours).set('minutes', correctMinutes).set('seconds', correctSeconds);
        }
        const { normalizedDate, formattedNormalizedDate } = (0, _utils1.normalizeDateTime)({
            originalDate: rawDate.toDate(),
            lang,
            format,
            includeEdgeDates,
            min,
            max
        });
        const isoDate = normalizedDate.toISOString();
        setCorrectDates((prevCorrectDates)=>({
                ...prevCorrectDates,
                input: formattedNormalizedDate,
                calendar: normalizedDate,
                time: normalizedDate
            }));
        setInnerDate(formattedNormalizedDate);
        if (onCommitDate) {
            onCommitDate(formattedNormalizedDate, {
                quarterInfo,
                originalDate: normalizedDate,
                isoDate
            });
        }
        if (onChangeValue) {
            onChangeValue(null, formattedNormalizedDate, {
                originalDate: normalizedDate,
                isoDate
            });
        }
    };
    const handleTimePick = (time)=>{
        if (disabled || readOnly) {
            return;
        }
        if (!time?.value) {
            return;
        }
        _datejs.customDayjs.locale(lang);
        let rawDate;
        if (!correctDates.calendar) {
            if (dateOnTimeSelectOnly) {
                rawDate = (0, _datejs.customDayjs)(dateOnTimeSelectOnly);
            } else {
                rawDate = (0, _datejs.customDayjs)();
            }
        } else {
            rawDate = (0, _datejs.customDayjs)(correctDates.calendar);
        }
        const { timeValues } = time;
        rawDate = rawDate.set('hours', timeValues.hour || 0).set('minutes', timeValues.minute || 0).set('seconds', timeValues.second || 0);
        const { normalizedDate, formattedNormalizedDate } = (0, _utils1.normalizeDateTime)({
            originalDate: rawDate.toDate(),
            lang,
            format,
            includeEdgeDates,
            min,
            max
        });
        const isoDate = normalizedDate.toISOString();
        const quarterInfo = getQuarterInfo(normalizedDate);
        setCorrectDates((prevCorrectDates)=>({
                ...prevCorrectDates,
                input: formattedNormalizedDate,
                calendar: normalizedDate,
                time: normalizedDate
            }));
        setInnerDate(formattedNormalizedDate);
        if (onCommitDate) {
            onCommitDate(formattedNormalizedDate, {
                quarterInfo,
                originalDate: normalizedDate,
                isoDate
            });
        }
        if (onChangeValue) {
            onChangeValue(null, formattedNormalizedDate, {
                originalDate: normalizedDate,
                isoDate
            });
        }
    };
    const updateExternalDate = (externalDate)=>{
        const { formattedDate, originalDate, dateValue, timeValue } = (0, _utils1.getFormattedDateTime)({
            value: externalDate,
            lang,
            format,
            dateFormat,
            timeFormat,
            includeEdgeDates,
            min,
            max
        });
        const { input: inputCorrectValue } = getFormattedCorrectInput({
            originalDate,
            formattedDate,
            dateValue,
            timeValue
        });
        setCorrectDates((prevCorrectDates)=>({
                ...prevCorrectDates,
                input: inputCorrectValue,
                calendar: inputCorrectValue ? dateValue || prevCorrectDates.calendar : undefined,
                time: inputCorrectValue ? timeValue || prevCorrectDates.time : undefined
            }));
        setInnerDate(formattedDate);
    };
    const handleBlur = (event)=>{
        if (!preserveInvalidOnBlur) {
            _datejs.customDayjs.locale(lang);
            const originalDate = correctDates.calendar;
            if (!originalDate) {
                if (onChangeValue) {
                    onChangeValue(event, correctDates.input, {
                        originalDate: undefined,
                        isoDate: ''
                    });
                }
                if (onCommitDate) {
                    onCommitDate(correctDates.input, {
                        quarterInfo: undefined,
                        originalDate: undefined,
                        isoDate: ''
                    });
                }
                return;
            }
            if (correctDates.time) {
                originalDate.setHours(correctDates.time.getHours(), correctDates.time.getMinutes(), correctDates.time.getSeconds());
            }
            setInnerDate(originalDate);
            if (!timeGridValue) {
                if (correctDates.calendar) {
                    setInnerDate(correctDates.calendar);
                }
            }
            if (onChangeValue) {
                onChangeValue(event, correctDates.input, {
                    originalDate,
                    isoDate: originalDate.toISOString()
                });
            }
            if (onCommitDate) {
                const quarterInfo = getQuarterInfo(originalDate);
                onCommitDate(correctDates.input, {
                    quarterInfo,
                    originalDate,
                    isoDate: originalDate.toISOString()
                });
            }
        }
        if (onBlur) {
            onBlur(event);
        }
    };
    (0, _react.useLayoutEffect)(()=>{
        if (outerValue !== undefined && !outerValue) {
            setInnerDate('');
            setCorrectDates({
                input: '',
                calendar: undefined,
                time: undefined
            });
        }
    }, [
        outerValue
    ]);
    return {
        format,
        dateVisibleValue,
        calendarGridValue,
        inputValue,
        timeVisibleValue,
        timeColumnsCount,
        errorClass,
        successClass,
        editedClass,
        handleChangeValue,
        handleSearch,
        handleCalendarPick,
        handleTimePick,
        handleBlur,
        updateExternalDate,
        getQuarterInfo,
        isDateEqualEdge
    };
};
