import { useState } from "preact/hooks";
import { HexColorPicker } from "react-colorful";
import { Modal } from "../../Modal";
import { Reminder } from "../../../api";
import { useDebouncedCallback } from "use-debounce";

type Props = {
    color: string;
    setReminder: (r: (reminder: Reminder) => Reminder) => void;
};

function colorToInt(hex: string) {
    return parseInt(hex.substring(1), 16);
}

export const Color = ({ color, setReminder }: Props) => {
    const [modalOpen, setModalOpen] = useState(false);

    return (
        <>
            {modalOpen && (
                <ColorModal
                    color={color}
                    setModalOpen={setModalOpen}
                    setReminder={setReminder}
                ></ColorModal>
            )}
            <button
                class="change-color button is-rounded is-small"
                onClick={() => {
                    setModalOpen(true);
                }}
            >
                <span class="is-sr-only">Choose embed color</span>
                <i class="fas fa-eye-dropper"></i>
            </button>
        </>
    );
};

const ColorModal = ({ setModalOpen, color, setReminder }) => {
    const setDebounced = useDebouncedCallback((color) => {
        setReminder((reminder: Reminder) => ({
            ...reminder,
            embed_color: colorToInt(color),
        }));
    }, 100);

    return (
        <Modal setModalOpen={setModalOpen} title={"Select Color"}>
            <div class="colorpicker-container">
                <HexColorPicker
                    color={color}
                    onChange={(color: string) => {
                        setDebounced(color);
                    }}
                ></HexColorPicker>
            </div>
            <br></br>
            <input
                class="input"
                id="colorInput"
                value={color}
                onInput={(ev) => {
                    setDebounced(ev.currentTarget.value);
                }}
            ></input>
        </Modal>
    );
};
