import React, { useCallback, useEffect, useRef } from 'react';
import { DatePicker } from '@wix/design-system';
import { useCloseOnAncestorScroll } from '../../../../hooks/useCloseOnAncestorScroll';
import { classes } from './Edit.st.css.js';
function isValidDate(value) {
    if (!value) {
        return true;
    }
    const date = value instanceof Date ? value : new Date(value);
    return !isNaN(date.getTime());
}
export const DateEdit = ({ value, onChange, onCommit, onCancel, inputRef, editTrigger, }) => {
    const datePickerRef = useRef(null);
    const validDate = isValidDate(value);
    // Auto-open calendar when entering edit mode via type-to-edit
    useEffect(() => {
        if (editTrigger &&
            typeof editTrigger === 'object' &&
            editTrigger.kind === 'type') {
            datePickerRef.current?.openCalendar();
        }
    }, [editTrigger]);
    const wrapperRef = useRef(null);
    // WDS DatePicker types declare closeCalendar but only _closeCalendar exists at runtime.
    const closeCalendar = useCallback(() => datePickerRef.current?._closeCalendar?.(), []);
    useCloseOnAncestorScroll(wrapperRef, closeCalendar, !!editTrigger);
    const dateValue = value
        ? value instanceof Date
            ? value
            : new Date(value)
        : null;
    const handleChange = useCallback((date) => {
        onChange(date);
        onCommit();
    }, [onChange, onCommit]);
    const handleKeyDown = useCallback((e) => {
        if (e.key === 'Escape') {
            e.preventDefault();
            onCancel();
        }
    }, [onCancel]);
    return (React.createElement("div", { ref: wrapperRef, onKeyDown: handleKeyDown, style: {
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
        } },
        React.createElement(DatePicker, { ref: datePickerRef, size: "small", inputProps: {
                border: 'none',
                prefix: React.createElement("span", null),
                ...(validDate
                    ? {}
                    : { value: typeof value === 'string' ? value : '' }),
                inputRef: (el) => {
                    if (inputRef) {
                        inputRef.current = el;
                    }
                },
            }, value: dateValue && !isNaN(dateValue.getTime()) ? dateValue : undefined, onChange: handleChange, popoverProps: { appendTo: 'window', moveBy: { y: 4 } }, className: classes.dateInput })));
};
//# sourceMappingURL=Edit.js.map