import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2024-2026 GoodData Corporation
import { useCallback } from "react";
import cx from "classnames";
import { FormattedMessage, defineMessages, useIntl } from "react-intl";
import { ValidationContextStore, createInvalidDatapoint, createInvalidNode, useValidationContextValue, } from "@gooddata/sdk-ui";
import { Datepicker, parseDate } from "../Datepicker/Datepicker.js";
import { Timepicker } from "../Timepicker/Timepicker.js";
import { normalizeTime } from "../Timepicker/utils/timeUtilities.js";
import { useIdPrefixed } from "../utils/useId.js";
import { DEFAULT_DROPDOWN_ZINDEX, TIME_ANCHOR } from "./constants.js";
const errorMessages = defineMessages({
    empty: { id: "recurrence.datetime.empty.error" },
    wrongFormat: { id: "recurrence.datetime.wrong.format.error" },
});
export function DateTime({ label, date, dateFormat, locale, timezone, onDateChange, weekStart, timeFormat, closeOnParentScroll, onKeyDownSubmit, }) {
    const { formatMessage } = useIntl();
    const dateFormatId = useIdPrefixed("label");
    const timezoneId = useIdPrefixed("timezone");
    const validationContextValue = useValidationContextValue(createInvalidNode({ id: "DateTime" }));
    const { setInvalidDatapoints, isValid } = validationContextValue;
    const invalidDatapoints = validationContextValue.getInvalidDatapoints();
    const validate = useCallback((selectedDate) => {
        const parsedDate = parseDate(selectedDate, dateFormat ?? "");
        if (selectedDate.length === 0) {
            setInvalidDatapoints(() => [
                createInvalidDatapoint({ message: formatMessage(errorMessages.empty) }),
            ]);
        }
        else if (parsedDate) {
            setInvalidDatapoints(() => []);
        }
        else {
            setInvalidDatapoints(() => [
                createInvalidDatapoint({ message: formatMessage(errorMessages.wrongFormat) }),
            ]);
        }
    }, [dateFormat, formatMessage, setInvalidDatapoints]);
    const handleDateChange = useCallback((selectedDate) => {
        const newDate = normalizeTime(date ?? undefined, selectedDate ?? undefined, TIME_ANCHOR);
        onDateChange(newDate, !!selectedDate);
    }, [date, onDateChange]);
    const handleDateBlur = useCallback((selectedDate) => {
        validate(selectedDate);
    }, [validate]);
    const handleDateValidate = useCallback((value) => {
        if (!isValid) {
            validate(value);
        }
    }, [isValid, validate]);
    const handleTimeChange = useCallback((selectedTime) => {
        const newDate = normalizeTime(selectedTime ?? undefined, date ?? undefined, TIME_ANCHOR);
        onDateChange(newDate, !!selectedTime);
    }, [date, onDateChange]);
    const handleOnDateInputKeyDown = (e) => {
        validate(e.currentTarget.value);
        onKeyDownSubmit?.(e);
    };
    const datePickerClassNames = cx("gd-recurrence-form-datetime-date s-recurrence-form-datetime-date", {
        "has-error": !isValid,
    });
    return (_jsx(ValidationContextStore, { value: validationContextValue, children: _jsxs("div", { className: "gd-recurrence-form-datetime s-recurrence-form-datetime gd-input-component", children: [
                _jsx("div", { className: "gd-label", children: label }), _jsxs("div", { className: "gd-recurrence-form-datetime-inner", children: [
                        _jsxs("div", { className: "gd-recurrence-form-date", children: [
                                _jsx(Datepicker, { className: datePickerClassNames, date: date ?? undefined, dateFormat: dateFormat, locale: locale, placeholder: dateFormat, onChange: handleDateChange, onValidateInput: handleDateValidate, onBlur: handleDateBlur, weekStart: weekStart ?? undefined, accessibilityConfig: {
                                        ariaDescribedBy: isValid
                                            ? dateFormatId
                                            : invalidDatapoints.map((d) => d.id).join(" "),
                                    }, onDateInputKeyDown: handleOnDateInputKeyDown }), isValid ? (_jsx("span", { className: "gd-recurrence-form-datetime-help", id: dateFormatId, children: _jsx(FormattedMessage, { id: "recurrence.datetime.format.help", values: { dateFormat } }) })) : (_jsx(_Fragment, { children: invalidDatapoints.map((datapoint) => (_jsx("span", { id: datapoint.id, className: "gd-recurrence-form-datetime-error-message", children: datapoint.message }, datapoint.id))) }))] }), _jsx(Timepicker, { className: "gd-recurrence-form-datetime-time s-recurrence-form-datetime-time", time: date, onChange: handleTimeChange, overlayPositionType: "sameAsTarget", overlayZIndex: DEFAULT_DROPDOWN_ZINDEX, timeAnchor: TIME_ANCHOR, timeFormat: timeFormat, closeOnParentScroll: closeOnParentScroll, ariaDescribedBy: timezone ? timezoneId : undefined })
                    ] }), timezone ? (_jsxs("div", { className: "gd-recurrence-form-datetime-timezone s-recurrence-form-datetime-timezone", children: [
                        _jsx("div", { className: "sr-only", id: timezoneId, children: _jsx(FormattedMessage, { id: "recurrence.datetime.timezone.help", values: { timezone } }) }), timezone] })) : null] }) }));
}
