import React, {useLayoutEffect, useMemo} from 'react';
// @ts-ignore
import iro from "@jaames/iro";

interface ColorPickerProps {
  h: number
  s: number
  onChange: (h: number, v: number) => void
}

const randomId = () => Math.floor(Math.random() * 100000);

export const HSColorPicker: React.FC<ColorPickerProps> = ({h, s, onChange}) => {
  const random = useMemo(() => `color-picker-${randomId()}`, []);

  useLayoutEffect(() => {
    // @ts-ignore
    const colorPicker = new iro.ColorPicker(`#${random}`, {
      color: {h, s: s * 100, v: 255},
      layout: [
        {
          component: iro.ui.Wheel,
          options: {}
        }
      ],
    });

    colorPicker.on("input:end", (color: { hsv: { h: number, s: number } }) => {
      onChange(color.hsv.h || 0, (color.hsv.s || 0) / 100);
    });

    return () => {
      const elem = document.getElementById(`color-picker-${random}`);
      if (elem === null) {
        return;
      }

      elem.innerHTML = "";
    };
  }, [h, s, onChange, random]);

  return <div id={random} style={{margin: "0 auto"}}/>;
};
