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;
};
import { jsx as _jsx, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
import { useCallback, useState, useMemo, useEffect, useRef } from 'react';
import { ColorPicker as ColorPickerAntd, Button } from 'antd';
import { debounce } from '../../../utils/debounce';
import { ColorStyled, ColorButtonCSS } from './color-picker.style';
const DELAY = 100;
const CLOSE_CODES = ['Escape', 'Enter'];
export const ColorPicker = (_a) => {
    var { onChange = () => void 0, onOpenChange = () => void 0, value } = _a, props = __rest(_a, ["onChange", "onOpenChange", "value"]);
    const [open, setOpen] = useState(false);
    const [inputValue, setInputValue] = useState(value);
    const triggerRef = useRef(null);
    // TODO: Remove all keyboard accessibility hacks once ColorPicker will be updated
    useEffect(() => {
        if (!open) {
            return () => { };
        }
        const handleClose = (event) => {
            if (!CLOSE_CODES.includes(event.code)) {
                return;
            }
            setOpen(false);
            onOpenChange(false);
            setTimeout(() => { var _a; return (_a = triggerRef.current) === null || _a === void 0 ? void 0 : _a.focus(); });
        };
        window.addEventListener('keydown', handleClose);
        return () => window.removeEventListener('keydown', handleClose);
    }, [open, onOpenChange]);
    const onChangeDebounced = useMemo(() => debounce(onChange, DELAY), [onChange]);
    const handleChange = useCallback((color, hex) => {
        setInputValue(color);
        onChangeDebounced(hex);
    }, [onChangeDebounced]);
    const handleOpenChange = useCallback((state) => {
        var _a;
        setOpen(state);
        if (state) {
            (_a = triggerRef.current) === null || _a === void 0 ? void 0 : _a.blur();
        }
        onOpenChange(state);
    }, [onOpenChange]);
    const setRef = useCallback((ref) => {
        triggerRef.current = ref;
    }, []);
    return (_jsx(_Fragment, { children: _jsx(ColorPickerAntd, Object.assign({ onChange: handleChange, onOpenChange: handleOpenChange, arrow: false, open: open, value: inputValue }, props, { children: _jsx(Button, { css: ColorButtonCSS(open), size: "small", ref: setRef, children: _jsx(ColorStyled, { color: value }) }) })) }));
};
