import { useEffect, useState } from '@wordpress/element';
import { ColorPalette } from '@wordpress/components';

import { OptionPanelProps } from '@components/DesignPanel/types';
import { getThemeOptions } from '@components/DesignPanel/Helpers';

export const ColorSwatch: React.FC<OptionPanelProps> = ({
  activeOptionValue,
  emitOptions,
  codex,
  modifierId,
}: any) => {
  const [color, setColor] = useState('#f00');
  const [colors, setColors] = useState<any[]>([]);

  useEffect(() => {
    if (codex === 'themeProvider.colors') {
      const colors = getThemeOptions('colors');
      colors.map((color: any) => {
        color.name = color.label;
        color.color = color.name;
        return color;
      });

      setColors(colors);
    }
  }, []);

  useEffect(() => {
    const color = getColorByValue(activeOptionValue);
    setColor(color?.color);
  }, [activeOptionValue]);

  // find color by color
  const getColorByColor = (color: string) => {
    return colors.find((c) => c.color === color);
  };

  const getColorByValue = (value: string) => {
    return colors.find((c) => c.value === value);
  };

  return (
    <div>
      <ColorPalette
        colors={colors}
        value={color}
        onChange={(color) => {
          const colorObject = getColorByColor(color);

          setColor(color);

          if (colorObject?.value) {
            emitOptions([
              {
                id: modifierId,
                value: colorObject?.value,
              },
            ]);
          }
        }}
      />
    </div>
  );
};

export default ColorSwatch;
