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, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import { Flex } from "@theme-ui/components";
import { Input } from "@theme-ui/components";
import { Icon } from "@notesnook/ui";
import { Icons } from "../icons";
import { useCallback, useEffect, useRef, useState } from "react";
import tinycolor from "tinycolor2";
import { HexColorPicker } from "react-colorful";
import { Button } from "../../components/button";
import { debounce } from "../../utils/debounce";
import { Popup } from "../components/popup";
export const DEFAULT_COLORS = [
    "#e91e63",
    "#9c27b0",
    "#673ab7",
    "#3f51b5",
    "#2196f3",
    "#03a9f4",
    "#00bcd4",
    "#009688",
    "#4caf50",
    "#8bc34a",
    "#cddc39",
    "#ffeb3b",
    "#ffc107",
    "#f44336"
];
const PALETTE_SIZE = [35, 35, 25];
export function ColorPicker(props) {
    const { color, onClear, onChange, title, onClose, expanded, onSave, colors = [], onDelete, editor } = props;
    const ref = useRef(null);
    const [isPickerOpen, setIsPickerOpen] = useState(expanded || false);
    const [currentColor, setCurrentColor] = useState(tinycolor(color || (colors === null || colors === void 0 ? void 0 : colors[0])).toHexString());
    const [deleteMode, setDeleteMode] = useState(false);
    const tColor = tinycolor(currentColor);
    const allColors = deleteMode ? colors : [...DEFAULT_COLORS, ...colors];
    useEffect(() => {
        if (!ref.current)
            return;
        if (isPickerOpen)
            ref.current.focus({ preventScroll: true });
    }, [isPickerOpen]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const onColorChange = useCallback(debounce((color) => {
        onChange(color);
    }, 500), [onChange]);
    return (_jsx(Popup, { title: title, onClose: onClose, children: _jsxs(Flex, { ref: ref, tabIndex: -1, sx: {
                bg: "background",
                flexDirection: "column",
                ".react-colorful": {
                    width: "auto",
                    height: 150
                },
                ".react-colorful__saturation": {
                    borderRadius: ["default", 0]
                },
                width: ["calc(100vw - 20px)", 250]
                //  width: ["auto", 250],
            }, children: [isPickerOpen ? (_jsxs(_Fragment, { children: [_jsx(HexColorPicker, { color: currentColor, onChange: (color) => {
                                setCurrentColor(color);
                                onColorChange(color);
                            }, onTouchEnd: () => onChange(currentColor), onMouseUp: () => onChange(currentColor) }), _jsxs(Flex, { sx: {
                                flexDirection: "row",
                                alignItems: "center",
                                justifyContent: "center"
                            }, children: [_jsx(Input, { variant: "clean", placeholder: "#000000", spellCheck: false, sx: {
                                        my: 2,
                                        p: 0,
                                        borderRadius: 0,
                                        fontSize: ["title", "title", "body"],
                                        color: "var(--paragraph-secondary)",
                                        width: [75, 75, 65],
                                        letterSpacing: 1.5,
                                        textAlign: "center"
                                    }, value: currentColor.toUpperCase(), maxLength: 7, onChange: (e) => {
                                        const { value } = e.target;
                                        if (!value)
                                            return;
                                        if (tinycolor(value, { format: "hex" }).isValid()) {
                                            setCurrentColor(value);
                                            onChange(value);
                                        }
                                    } }), onSave && (_jsx(PaletteButton, { sx: {
                                        boxShadow: "none"
                                    }, disabled: allColors.includes(currentColor), icon: Icons.save, iconSize: 18, onClick: () => onSave(currentColor), title: "Save color" }))] })] })) : null, _jsxs(Flex, { children: [_jsxs(Flex, { className: "hide-scrollbar", sx: {
                                flex: 1,
                                p: 1,
                                overflowX: ["auto", "hidden"],
                                flexWrap: ["nowrap", "wrap"],
                                overflowY: ["hidden", "auto"]
                            }, children: [!deleteMode && (_jsx(PaletteButton, { icon: Icons.colorClear, onClick: onClear, title: "Clear color", iconSize: 15 })), _jsx(PaletteButton, { icon: Icons.delete, iconColor: deleteMode ? "var(--icon-error)" : "icon", bg: deleteMode ? "var(--background-error)" : "transparent", onClick: () => setDeleteMode((s) => !s), title: deleteMode
                                        ? "Disable delete mode"
                                        : "Enable delete mode for deleting custom colors", iconSize: 18 }), !deleteMode && (_jsx(PaletteButton, { icon: Icons.palette, iconColor: tColor.isDark() ? "white" : "icon", onClick: () => {
                                        setIsPickerOpen((s) => {
                                            if (s) {
                                                editor.commands.focus();
                                            }
                                            else {
                                                const onSelectionChange = () => {
                                                    setIsPickerOpen(false);
                                                    editor.off("selectionUpdate", onSelectionChange);
                                                };
                                                editor.on("selectionUpdate", onSelectionChange);
                                            }
                                            return !s;
                                        });
                                    }, title: "Choose custom color", iconSize: 18, bg: currentColor })), allColors.map((colorItem) => (_jsx(PaletteButton, { title: deleteMode ? "Click to delete this color" : colorItem, bg: colorItem, iconSize: 15, iconColor: "white", icon: deleteMode && colors.includes(colorItem)
                                        ? Icons.close
                                        : undefined, onClick: () => {
                                        if (deleteMode) {
                                            onDelete === null || onDelete === void 0 ? void 0 : onDelete(colorItem);
                                            return;
                                        }
                                        setCurrentColor(colorItem);
                                        onChange(colorItem);
                                    }, sx: { mb: [0, 1, 1] } }, colorItem)))] }), onClose && (_jsx(Button, { variant: "icon", sx: {
                                display: ["block", "none"],
                                px: 2,
                                width: "50px",
                                alignSelf: "center"
                            }, onClick: onClose, children: _jsx(Icon, { path: Icons.close, size: "big" }) }))] })] }) }));
}
function PaletteButton(props) {
    const { sx, iconColor, icon, iconSize = 20, bg } = props, restProps = __rest(props, ["sx", "iconColor", "icon", "iconSize", "bg"]);
    return (_jsx(Button, Object.assign({ variant: "icon", sx: Object.assign({ flexShrink: 0, width: PALETTE_SIZE, height: PALETTE_SIZE, borderRadius: 50, boxShadow: "menu", p: 0, ml: [2, 2, 1], bg, ":hover:not(:disabled):not(:active)": {
                bg: (bg === null || bg === void 0 ? void 0 : bg.startsWith("#"))
                    ? tinycolor(bg).darken(5).toRgbString()
                    : "hover"
            } }, sx) }, restProps, { children: icon && _jsx(Icon, { path: icon, color: iconColor, size: iconSize }) })));
}
