"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimePicker = void 0;
const react_1 = __importStar(require("react"));
const use_forwarded_ref_1 = require("@bedrock-layout/use-forwarded-ref");
const useNativeValidity_1 = require("../../../utils/useNativeValidity");
const Clock_1 = require("../../icons/Clock");
const Input_styled_1 = require("../input/Input.styled");
const TimePicker_styled_1 = require("./TimePicker.styled");
const TimePickerModal_1 = require("./TimePickerModal");
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 = (_a, ref) => {
    var { className, label, pinnedLabel = false, error, withSeconds = false, minuteStep = 1, secondStep = 1, value, defaultValue, onChange, onFocus, onBlur, disabled, readOnly, id, modalTitle, okLabel = "OK", cancelLabel = "Cancel" } = _a, rest = __rest(_a, ["className", "label", "pinnedLabel", "error", "withSeconds", "minuteStep", "secondStep", "value", "defaultValue", "onChange", "onFocus", "onBlur", "disabled", "readOnly", "id", "modalTitle", "okLabel", "cancelLabel"]);
    assertStep("minuteStep", minuteStep);
    if (withSeconds) {
        assertStep("secondStep", secondStep);
    }
    const isControlled = value !== undefined;
    const [internalValue, setInternalValue] = (0, react_1.useState)(defaultValue !== null && defaultValue !== void 0 ? defaultValue : "");
    const currentValue = isControlled ? (value !== null && value !== void 0 ? value : "") : internalValue;
    const [focused, setFocused] = (0, react_1.useState)(false);
    const validity = (0, useNativeValidity_1.useNativeValidity)(error);
    const { revalidate } = validity;
    const inputRef = (0, use_forwarded_ref_1.useForwardedRef)(ref);
    const generatedId = (0, react_1.useId)();
    const inputId = id !== null && id !== void 0 ? id : (label ? generatedId : undefined);
    const [modalOpen, setModalOpen] = (0, react_1.useState)(false);
    const handleChange = (0, react_1.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 = (0, react_1.useCallback)((e) => {
        setFocused(true);
        onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
    }, [onFocus]);
    const handleBlur = (0, react_1.useCallback)((e) => {
        setFocused(false);
        validity.onBlur(e);
        onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
    }, [onBlur, validity]);
    (0, react_1.useEffect)(() => {
        revalidate(inputRef.current);
    }, [currentValue, revalidate, inputRef]);
    const openModal = (0, react_1.useCallback)(() => {
        setModalOpen(true);
    }, []);
    const closeModal = (0, react_1.useCallback)(() => {
        var _a;
        setModalOpen(false);
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
    }, [inputRef]);
    const confirmModal = (0, react_1.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_1.default.createElement(Input_styled_1.StyledLabel, { htmlFor: inputId, floating: floating, error: finalError }, label))
        : null;
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(Input_styled_1.StyledWrapper, { className: className, focused: focused, disabled: Boolean(disabled), readOnly: Boolean(readOnly), error: finalError },
            react_1.default.createElement(Input_styled_1.StyledInputContainer, null,
                labelElem,
                react_1.default.createElement(TimePicker_styled_1.StyledTimeInput, Object.assign({ 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_1.default.createElement(Input_styled_1.StyledSuffix, null,
                react_1.default.createElement(TimePicker_styled_1.StyledSuffixButton, { type: "button", onClick: openModal, disabled: disabled, "aria-label": "Open time picker" },
                    react_1.default.createElement(Clock_1.Clock, null)))),
        react_1.default.createElement(TimePickerModal_1.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 = (0, react_1.forwardRef)(TimePickerInner);
TimePickerRef.displayName = "TimePicker";
TimePickerRef.toString = () => Input_styled_1.StyledWrapper.toString();
const TimePicker = TimePickerRef;
exports.TimePicker = TimePicker;
//# sourceMappingURL=TimePicker.js.map