"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get datePickerConfig () {
        return datePickerConfig;
    },
    get datePickerRoot () {
        return datePickerRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _classnames = /*#__PURE__*/ _interop_require_default(require("classnames"));
const _utils = require("../../../utils");
const _dateHelper = require("../utils/dateHelper");
const _useDatePicker = require("../hooks/useDatePicker");
const _DatePickertokens = require("../DatePicker.tokens");
const _DatePickerBasestyles = require("../DatePickerBase.styles");
const _useKeyboardNavigation = require("../hooks/useKeyboardNavigation");
const _utils1 = require("../utils");
const _ui = require("../ui");
const _FloatingPopover = require("../FloatingPopover");
const _base = require("./variations/_size/base");
const _base1 = require("./variations/_view/base");
const _base2 = require("./variations/_hint-view/base");
const _base3 = require("./variations/_hint-size/base");
const _base4 = require("./variations/_tooltip-size/base");
const _base5 = require("./variations/_disabled/base");
const _base6 = require("./variations/_readonly/base");
const _SingleDatestyles = require("./SingleDate.styles");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const datePickerRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ className, name, autoComplete, // controlled
    value: outerValue, opened: outerOpened, defaultDate = '', preserveInvalidOnBlur, // variations
    view, size, readOnly = false, disabled = false, appearance, hasClearDivider, stretched, valueError, valueSuccess, valueEdited, // layout
    label, labelPlacement = 'outer', keepPlaceholder, required = false, requiredPlacement = 'right', hasRequiredIndicator = false, placeholder, leftHelper, contentLeft, contentRight, textBefore, textAfter, // hint
    hintTrigger = 'hover', hintText, hintView = 'default', hintSize = 'm', hintTargetIcon, hintTargetPlacement = 'outer', hintPlacement = 'auto', hintHasArrow, hintOffset = [
        0,
        0
    ], hintWidth, hintContentLeft, // popover-container
    frame = 'document', usePortal = false, zIndex, placement = [
        'top',
        'bottom'
    ], closeOnOverlayClick = true, closeOnEsc = true, closeAfterDateSelect = true, offset, disableFlip, // calendar
    format = 'DD.MM.YYYY', lang = 'ru', maskWithFormat, min, max, renderFromDate, includeEdgeDates = false, eventTooltipOptions, eventList, disabledList, eventMonthList, disabledMonthList, eventQuarterList, disabledQuarterList, eventYearList, disabledYearList, type = 'Days', calendarContainerWidth, calendarContainerHeight, dateShortcuts, dateShortcutsPlacement = 'left', dateShortcutsWidth, onChangeValue, onCommitDate, onToggle, onFocus, onBlur, onChange, ...rest }, ref)=>{
        const inputRef = (0, _react.useRef)(null);
        const innerRef = (0, _react.useRef)(null);
        const calendarRootRef = (0, _react.useRef)(null);
        const floatingPopoverRef = (0, _react.useRef)(null);
        const [isInnerOpen, setIsInnerOpen] = (0, _react.useState)(false);
        const openedValue = outerOpened ?? isInnerOpen;
        const dateFormatDelimiter = (0, _dateHelper.getDateFormatDelimiter)(format);
        const [innerDate, setInnerDate] = (0, _react.useState)(defaultDate || '');
        const dateValue = outerValue ?? innerDate;
        const initialValues = (0, _utils1.getFormattedDates)({
            value: dateValue,
            delimiter: dateFormatDelimiter,
            lang,
            format,
            includeEdgeDates,
            min,
            max
        });
        const [correctDates, setCorrectDates] = (0, _react.useState)({
            calendar: initialValues.originalDate,
            input: initialValues.formattedDate
        });
        const calendarValue = initialValues.originalDate;
        const inputValue = initialValues.formattedDate;
        const calendarContainerWidthValue = calendarContainerWidth ? (0, _utils.getSizeValueFromProp)(calendarContainerWidth, 'rem') : undefined;
        const calendarContainerHeightValue = calendarContainerHeight ? (0, _utils.getSizeValueFromProp)(calendarContainerHeight, 'rem') : undefined;
        const { datePickerErrorClass, datePickerSuccessClass, datePickerEditedClass, handleChangeValue, handleCalendarPick: onCalendarPick, handleSearch, getQuarterInfo, updateExternalDate } = (0, _useDatePicker.useDatePicker)({
            currentValue: inputValue,
            format,
            lang,
            disabled,
            readOnly,
            maskWithFormat,
            valueError,
            valueSuccess,
            valueEdited,
            name,
            type,
            min,
            max,
            includeEdgeDates,
            setCorrectDates,
            setInnerDate,
            dateFormatDelimiter,
            onChangeValue,
            onCommitDate,
            onChange
        });
        const handleToggle = (innerOpened, event)=>{
            if (disabled || readOnly) {
                return;
            }
            const isCalendarOpen = event?.target === inputRef?.current && event.code !== _useKeyboardNavigation.keys.Escape ? true : innerOpened;
            if (onToggle) {
                onToggle(isCalendarOpen, event);
            }
            setIsInnerOpen(isCalendarOpen);
        };
        const handleCalendarRootClick = (event)=>{
            if (disabled || readOnly) {
                return;
            }
            if (isInnerOpen && stretched && event.target === calendarRootRef?.current) {
                setIsInnerOpen(false);
                if (onToggle) {
                    onToggle(false, event);
                }
            }
        };
        const { onKeyDown } = (0, _useKeyboardNavigation.useKeyNavigation)({
            isCalendarOpen: openedValue,
            format,
            maskWithFormat,
            delimiter: dateFormatDelimiter,
            closeOnEsc,
            onToggle: handleToggle
        });
        const handleBlur = (event)=>{
            if (!preserveInvalidOnBlur && !calendarValue && correctDates.calendar) {
                setInnerDate(new Date(correctDates.calendar));
                if (onChangeValue) {
                    onChangeValue(event, correctDates.input, correctDates.calendar, correctDates.calendar.toISOString());
                }
                if (onCommitDate) {
                    const dateInfo = getQuarterInfo(correctDates.calendar);
                    (0, _utils1.invokeOnCommitDate)({
                        callback: onCommitDate,
                        value: correctDates.input,
                        formattedValues: {
                            error: false,
                            success: true,
                            dateInfo,
                            originalDate: correctDates.calendar,
                            isoDate: correctDates.calendar.toISOString()
                        }
                    });
                }
                if (onChange) {
                    onChange({
                        target: {
                            value: correctDates.input,
                            originalDate: correctDates.calendar,
                            isoDate: correctDates.calendar.toISOString(),
                            name
                        }
                    });
                }
            }
            if (onBlur) {
                onBlur(event);
            }
        };
        const handleCalendarPick = (date, dateInfo)=>{
            onCalendarPick(date, dateInfo);
            if (closeAfterDateSelect) {
                setIsInnerOpen(false);
                handleToggle(false);
            }
        };
        (0, _react.useLayoutEffect)(()=>{
            if (!dateValue) {
                updateExternalDate(defaultDate);
            }
        }, [
            defaultDate,
            format,
            lang
        ]);
        (0, _react.useLayoutEffect)(()=>{
            if (outerValue !== undefined && !outerValue) {
                setInnerDate('');
                setCorrectDates({
                    calendar: undefined,
                    input: ''
                });
            }
        }, [
            outerValue
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            view: view,
            size: size,
            className: (0, _classnames.default)(_DatePickertokens.classes.datePickerRoot, className, {
                [_DatePickertokens.classes.datePickerstretched]: stretched
            }),
            disabled: disabled,
            readOnly: !disabled && readOnly,
            ref: ref,
            eventTooltipSize: eventTooltipOptions?.size,
            ...hintText && {
                hintView,
                hintSize
            },
            ...rest
        }, /*#__PURE__*/ _react.default.createElement(_FloatingPopover.FloatingPopover, {
            ref: floatingPopoverRef,
            opened: openedValue,
            onToggle: handleToggle,
            offset: offset,
            zIndex: zIndex,
            placement: placement,
            disableFlip: disableFlip,
            closeOnOverlayClick: closeOnOverlayClick,
            closeOnEsc: closeOnEsc,
            portal: usePortal ? frame : undefined,
            target: (referenceRef)=>/*#__PURE__*/ _react.default.createElement(_SingleDatestyles.StyledInput, {
                    ref: inputRef,
                    inputWrapperRef: referenceRef,
                    className: (0, _classnames.default)(datePickerErrorClass, datePickerSuccessClass, datePickerEditedClass),
                    value: inputValue,
                    size: size,
                    readOnly: readOnly,
                    disabled: disabled,
                    placeholder: placeholder,
                    contentLeft: contentLeft,
                    contentRight: contentRight,
                    textBefore: textBefore,
                    textAfter: textAfter,
                    onChange: handleChangeValue,
                    onSearch: handleSearch,
                    onFocus: onFocus,
                    onBlur: handleBlur,
                    onKeyDown: onKeyDown,
                    required: required,
                    requiredPlacement: requiredPlacement,
                    hasRequiredIndicator: hasRequiredIndicator,
                    label: label,
                    labelPlacement: labelPlacement,
                    keepPlaceholder: keepPlaceholder,
                    autoComplete: autoComplete,
                    appearance: appearance,
                    hasDivider: hasClearDivider,
                    ...hintText ? {
                        hintText,
                        hintView,
                        hintSize,
                        hintTrigger,
                        hintTargetIcon,
                        hintPlacement,
                        hintHasArrow,
                        hintOffset,
                        hintWidth,
                        hintContentLeft,
                        hintTargetPlacement
                    } : {
                        hintText: undefined
                    }
                })
        }, /*#__PURE__*/ _react.default.createElement(Root, {
            ref: calendarRootRef,
            view: view,
            size: size,
            className: (0, _classnames.default)(_DatePickertokens.classes.datePickerRoot, className, {
                [_DatePickertokens.classes.datePickerstretched]: stretched
            }),
            disabled: disabled,
            readOnly: !disabled && readOnly,
            onClick: handleCalendarRootClick
        }, /*#__PURE__*/ _react.default.createElement(_DatePickerBasestyles.StyledCalendarContent, {
            innerWidth: calendarContainerWidthValue,
            innerHeight: calendarContainerHeightValue
        }, dateShortcuts?.length ? /*#__PURE__*/ _react.default.createElement(_ui.StyledShortcutList, {
            items: dateShortcuts,
            setShortcutDate: onCalendarPick,
            dateShortcutsWidth: dateShortcutsWidth,
            calendarContainerHeight: calendarContainerHeight,
            dateShortcutsPlacement: dateShortcutsPlacement
        }) : null, /*#__PURE__*/ _react.default.createElement(_DatePickerBasestyles.StyledCalendar, {
            className: (0, _classnames.default)({
                [_DatePickertokens.classes.datePickerCalendarstretched]: stretched
            }),
            innerWidth: calendarContainerWidthValue,
            innerHeight: calendarContainerHeightValue,
            size: size,
            value: calendarValue,
            type: type,
            eventTooltipOptions: eventTooltipOptions,
            eventList: eventList,
            disabledList: disabledList,
            eventMonthList: eventMonthList,
            disabledMonthList: disabledMonthList,
            eventQuarterList: eventQuarterList,
            disabledQuarterList: disabledQuarterList,
            eventYearList: eventYearList,
            disabledYearList: disabledYearList,
            min: min,
            max: max,
            renderFromDate: renderFromDate,
            includeEdgeDates: includeEdgeDates,
            isRange: false,
            locale: lang,
            onChangeValue: handleCalendarPick
        })))), leftHelper && /*#__PURE__*/ _react.default.createElement(_SingleDatestyles.LeftHelper, {
            className: (0, _classnames.default)(datePickerErrorClass, datePickerSuccessClass, datePickerEditedClass)
        }, leftHelper), /*#__PURE__*/ _react.default.createElement(_DatePickerBasestyles.InputHidden, {
            type: "hidden",
            datatype: "datepicker-single",
            name: name,
            value: inputValue,
            ref: innerRef,
            ..._utils.noop
        }));
    });
const datePickerConfig = {
    name: 'DatePicker',
    tag: 'div',
    layout: datePickerRoot,
    base: _SingleDatestyles.base,
    variations: {
        view: {
            css: _base1.base
        },
        size: {
            css: _base.base
        },
        eventTooltipSize: {
            css: _base4.base
        },
        hintView: {
            css: _base2.base
        },
        hintSize: {
            css: _base3.base
        },
        disabled: {
            css: _base5.base,
            attrs: true
        },
        readOnly: {
            css: _base6.base,
            attrs: true
        }
    },
    defaults: {
        size: 'm',
        view: 'default',
        eventTooltipSizeCSS: 'm'
    }
};
