import React, { forwardRef, useCallback, useEffect, useId, useState, } from "react";
import { useForwardedRef } from "@bedrock-layout/use-forwarded-ref";
import { useNativeValidity } from "../../../utils/useNativeValidity.js";
import { Clock } from "../../icons/Clock.js";
import { StyledInputContainer, StyledLabel, StyledSuffix, StyledWrapper, } from "../input/Input.styled.js";
import { StyledSuffixButton, StyledTimeInput, } from "./TimePicker.styled.js";
import { TimePickerModal } from "./TimePickerModal.js";
const PATTERN_HHMM = "(?:[01]\\d|2[0-3]):[0-5]\\d";
const PATTERN_HHMMSS = "(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";
const MAX_LEN_HHMM = 5;
const MAX_LEN_HHMMSS = 8;
const assertStep = (name, step) => {
    if (!Number.isInteger(step) || step < 1 || step > 60) {
        throw new Error(`TimePicker: \`${name}\` must be an integer between 1 and 60, got ${String(step)}`);
    }
};
const TimePickerInner = ({ className, label, pinnedLabel = false, error, withSeconds = false, minuteStep = 1, secondStep = 1, value, defaultValue, onChange, onFocus, onBlur, disabled, readOnly, id, modalTitle, okLabel = "OK", cancelLabel = "Cancel", ...rest }, ref) => {
    assertStep("minuteStep", minuteStep);
    if (withSeconds) {
        assertStep("secondStep", secondStep);
    }
    const isControlled = value !== undefined;
    const [internalValue, setInternalValue] = useState(defaultValue !== null && defaultValue !== void 0 ? defaultValue : "");
    const currentValue = isControlled ? (value !== null && value !== void 0 ? value : "") : internalValue;
    const [focused, setFocused] = useState(false);
    const validity = useNativeValidity(error);
    const { revalidate } = validity;
    const inputRef = useForwardedRef(ref);
    const generatedId = useId();
    const inputId = id !== null && id !== void 0 ? id : (label ? generatedId : undefined);
    const [modalOpen, setModalOpen] = useState(false);
    const handleChange = useCallback((e) => {
        const next = e.target.value;
        if (!isControlled) {
            setInternalValue(next);
        }
        validity.onChange(e);
        onChange === null || onChange === void 0 ? void 0 : onChange(next);
    }, [isControlled, onChange, validity]);
    const handleFocus = useCallback((e) => {
        setFocused(true);
        onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
    }, [onFocus]);
    const handleBlur = useCallback((e) => {
        setFocused(false);
        validity.onBlur(e);
        onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
    }, [onBlur, validity]);
    useEffect(() => {
        revalidate(inputRef.current);
    }, [currentValue, revalidate, inputRef]);
    const openModal = useCallback(() => {
        setModalOpen(true);
    }, []);
    const closeModal = useCallback(() => {
        var _a;
        setModalOpen(false);
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
    }, [inputRef]);
    const confirmModal = useCallback((next) => {
        var _a;
        if (!isControlled) {
            setInternalValue(next);
        }
        onChange === null || onChange === void 0 ? void 0 : onChange(next);
        setModalOpen(false);
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
    }, [isControlled, onChange, inputRef]);
    const hasValue = currentValue.length > 0;
    const floating = Boolean(label) && (pinnedLabel || focused || hasValue);
    const placeholder = withSeconds ? "--:--:--" : "--:--";
    const pattern = withSeconds ? PATTERN_HHMMSS : PATTERN_HHMM;
    const maxLength = withSeconds ? MAX_LEN_HHMMSS : MAX_LEN_HHMM;
    const finalError = validity.finalError;
    const labelElem = label
        ? (React.createElement(StyledLabel, { htmlFor: inputId, floating: floating, error: finalError }, label))
        : null;
    return (React.createElement(React.Fragment, null,
        React.createElement(StyledWrapper, { className: className, focused: focused, disabled: Boolean(disabled), readOnly: Boolean(readOnly), error: finalError },
            React.createElement(StyledInputContainer, null,
                labelElem,
                React.createElement(StyledTimeInput, { ref: inputRef, ...rest, id: inputId, type: "text", inputMode: "numeric", autoComplete: "off", value: currentValue, placeholder: placeholder, pattern: pattern, maxLength: maxLength, disabled: disabled, readOnly: readOnly, onChange: handleChange, onFocus: handleFocus, onBlur: handleBlur, onInvalid: validity.onInvalid, "data-error": finalError })),
            React.createElement(StyledSuffix, null,
                React.createElement(StyledSuffixButton, { type: "button", onClick: openModal, disabled: disabled, "aria-label": "Open time picker" },
                    React.createElement(Clock, null)))),
        React.createElement(TimePickerModal, { isOpen: modalOpen, initialValue: currentValue, withSeconds: withSeconds, minuteStep: minuteStep, secondStep: secondStep, readOnly: Boolean(readOnly), title: modalTitle, okLabel: okLabel, cancelLabel: cancelLabel, onClose: closeModal, onConfirm: confirmModal })));
};
const TimePickerRef = forwardRef(TimePickerInner);
TimePickerRef.displayName = "TimePicker";
TimePickerRef.toString = () => StyledWrapper.toString();
const TimePicker = TimePickerRef;
export { TimePicker };
//# sourceMappingURL=TimePicker.js.map