"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const acui_1 = require("@Acme Corporation/acui");
const DatePicker = (0, react_1.forwardRef)(({ name, label, helperText, error: externalError, isRequired = false, isDisabled = false, isReadOnly = false, isInvalid: externalInvalid, size = 'md', format = 'YYYY-MM-DD', minDate, maxDate, showTodayButton = true, todayButtonLabel = 'Set to today', showClearButton = true, clearButtonLabel = 'Clear date', className = '', wrapperClassName = '', labelClassName = '', inputClassName = '', errorClassName = '', helperTextClassName = '', todayButtonClassName = '', clearButtonClassName = '', validateOnChange = false, validateOnBlur = true, onChange, onBlur, value, defaultValue, ...props }, ref) => {
    const theme = (0, acui_1.useTheme)();
    const formContext = react_1.default.useContext(FormContext);
    const [localValue, setLocalValue] = (0, react_1.useState)(value ?? defaultValue ?? '');
    const inputRef = react_1.default.useRef(null);
    const combinedRef = react_1.default.useCallback((node) => {
        inputRef.current = node;
        if (typeof ref === 'function') {
            ref(node);
        }
        else if (ref) {
            ref.current = node;
        }
    }, [ref]);
    const { errors = {}, touched = {}, setFieldValue, setFieldTouched, setFieldError } = formContext || {};
    const error = externalError || errors[name];
    const isInvalid = externalInvalid || (touched[name] && !!error);
    const isControlled = value !== undefined;
    const formatDate = (0, react_1.useCallback)((date) => {
        if (!date)
            return '';
        try {
            const d = new Date(date);
            if (isNaN(d.getTime()))
                return date;
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            switch (format) {
                case 'MM/DD/YYYY':
                    return `${month}/${day}/${year}`;
                case 'DD/MM/YYYY':
                    return `${day}/${month}/${year}`;
                case 'YYYY-MM-DD':
                default:
                    return `${year}-${month}-${day}`;
            }
        }
        catch {
            return date;
        }
    }, [format]);
    const parseDate = (0, react_1.useCallback)((date) => {
        if (!date)
            return '';
        try {
            let d;
            switch (format) {
                case 'MM/DD/YYYY':
                    const [month, day, year] = date.split('/');
                    d = new Date(Number(year), Number(month) - 1, Number(day));
                    break;
                case 'DD/MM/YYYY':
                    const [dDay, dMonth, dYear] = date.split('/');
                    d = new Date(Number(dYear), Number(dMonth) - 1, Number(dDay));
                    break;
                case 'YYYY-MM-DD':
                default:
                    d = new Date(date);
            }
            if (isNaN(d.getTime()))
                return date;
            return d.toISOString().split('T')[0];
        }
        catch {
            return date;
        }
    }, [format]);
    const handleChange = (0, react_1.useCallback)((e) => {
        const inputValue = e.target.value;
        const parsedValue = parseDate(inputValue);
        if (!isControlled) {
            setLocalValue(parsedValue);
        }
        onChange?.(e);
        if (formContext && validateOnChange) {
            setFieldValue(name, parsedValue);
        }
    }, [isControlled, onChange, formContext, name, setFieldValue, validateOnChange, parseDate]);
    const handleBlur = (0, react_1.useCallback)((e) => {
        const inputValue = e.target.value;
        const parsedValue = parseDate(inputValue);
        if (!isControlled) {
            setLocalValue(parsedValue);
        }
        onBlur?.(e);
        if (formContext && validateOnBlur) {
            setFieldTouched(name, true);
        }
    }, [onBlur, formContext, name, setFieldTouched, validateOnBlur, isControlled, parseDate]);
    const handleTodayClick = (0, react_1.useCallback)(() => {
        const today = new Date();
        const dateString = today.toISOString().split('T')[0];
        if (!isControlled) {
            setLocalValue(dateString);
        }
        // Trigger change event
        const event = {
            target: {
                name,
                value: dateString,
            },
        };
        onChange?.(event);
        if (formContext) {
            setFieldValue(name, dateString);
        }
    }, [onChange, formContext, name, setFieldValue, isControlled]);
    const handleClearClick = (0, react_1.useCallback)(() => {
        if (!isControlled) {
            setLocalValue('');
        }
        // Trigger change event
        const event = {
            target: {
                name,
                value: '',
            },
        };
        onChange?.(event);
        if (formContext) {
            setFieldValue(name, '');
        }
    }, [onChange, formContext, name, setFieldValue, isControlled]);
    const displayValue = react_1.default.useMemo(() => {
        const dateValue = isControlled ? value : localValue;
        return formatDate(dateValue);
    }, [isControlled, value, localValue, formatDate]);
    const labelId = react_1.default.useId();
    const errorId = react_1.default.useId();
    const helperTextId = react_1.default.useId();
    const ariaInvalid = isInvalid ? 'true' : undefined;
    const ariaRequired = isRequired ? 'true' : undefined;
    const ariaDescribedBy = error ? errorId : helperText ? helperTextId : undefined;
    return ((0, jsx_runtime_1.jsxs)("div", { className: `bf-date-picker-wrapper ${wrapperClassName}`, "data-size": size, "data-invalid": isInvalid, "data-disabled": isDisabled, "data-readonly": isReadOnly, children: [label && ((0, jsx_runtime_1.jsxs)("label", { id: labelId, htmlFor: name, className: `bf-date-picker-label ${labelClassName}`, children: [label, isRequired && (0, jsx_runtime_1.jsx)("span", { className: "bf-required-mark", "aria-hidden": "true", children: "*" })] })), (0, jsx_runtime_1.jsxs)("div", { className: "bf-date-picker-container", children: [(0, jsx_runtime_1.jsx)("input", { ref: combinedRef, type: "date", id: name, name: name, value: displayValue, onChange: handleChange, onBlur: handleBlur, disabled: isDisabled, readOnly: isReadOnly, required: isRequired, min: minDate, max: maxDate, "aria-labelledby": label ? labelId : undefined, "aria-invalid": ariaInvalid, "aria-required": ariaRequired, "aria-describedby": ariaDescribedBy, className: `bf-date-picker-input ${inputClassName} ${className}`, ...props }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-date-picker-buttons", children: [showTodayButton && !isDisabled && !isReadOnly && ((0, jsx_runtime_1.jsx)("button", { type: "button", className: `bf-date-picker-today-button ${todayButtonClassName}`, onClick: handleTodayClick, tabIndex: -1, "aria-label": todayButtonLabel, children: (0, jsx_runtime_1.jsx)("span", { "aria-hidden": "true", children: "\uD83D\uDCC5" }) })), showClearButton && !isDisabled && !isReadOnly && displayValue && ((0, jsx_runtime_1.jsx)("button", { type: "button", className: `bf-date-picker-clear-button ${clearButtonClassName}`, onClick: handleClearClick, tabIndex: -1, "aria-label": clearButtonLabel, children: (0, jsx_runtime_1.jsx)("span", { "aria-hidden": "true", children: "\u2715" }) }))] })] }), error && ((0, jsx_runtime_1.jsx)("div", { id: errorId, className: `bf-date-picker-error ${errorClassName}`, role: "alert", "aria-live": "assertive", children: error })), helperText && !error && ((0, jsx_runtime_1.jsx)("div", { id: helperTextId, className: `bf-date-picker-helper-text ${helperTextClassName}`, role: "status", children: helperText }))] }));
});
DatePicker.displayName = 'DatePicker';
exports.default = (0, react_1.memo)(DatePicker);
//# sourceMappingURL=DatePicker.js.map