import { useCallback, useRef, useState } from 'react';

import { HexColorInput, RgbaStringColorPicker } from 'react-colorful';

// @ts-ignore
import config from '../../../../../../nitrogen.config.js';
import wysiwygColors from '../../utils/defaultWysiwygColors.js';
import hexToRgba from '../../utils/hexToRgba.js';
import rgba2hex from '../../utils/rgbaToHex.js';
import useClickOutside from '../../utils/useClickOutside.js';

import './ColorPicker.scss';

let wysiwyg_colors = wysiwygColors;

if (config.wysiwygColors) {
  wysiwyg_colors = config.wysiwygColors;
  wysiwyg_colors = Object.keys(wysiwyg_colors).flatMap((color) => [
    (wysiwyg_colors as { [key: string]: string })[color],
    color,
  ]);
}

const WYSIWYG_COLORS: string[] = (wysiwyg_colors as string[])
  .filter((_, i) => i % 2 === 0)
  .map((color) => hexToRgba(color));

type Props = {
  color: string;
  onChange: (color: string) => void;
  inheritVal?: boolean;
  className?: string;
};

function getColorInRgb(color: string) {
  if (!color || color.startsWith('rgb')) {
    return color;
  }
  return hexToRgba(color);
}
function getColorInHex(color: string) {
  if (color && color.startsWith('rgb')) {
    return rgba2hex(color);
  }
  return color;
}

// TODO: Add section for custom colors, and section for default colors

export default function ColorPicker({
  color,
  onChange,
  inheritVal,
  className = '',
}: Props) {
  const popover = useRef(null);
  const [isOpen, toggle] = useState(false);

  const close = useCallback(() => toggle(false), []);
  useClickOutside(popover, close);

  return (
    <div
      className={`color-picker ${className} ${
        isOpen ? 'color-picker--open' : ''
      }`}
    >
      <div
        className={`color-picker__container`}
        style={{
          backgroundColor: color,
        }}
        onClick={() => toggle(true)}
      >
        <div
          className={`color-picker__container__btn  ${
            inheritVal ? 'color-picker__container__btn--inherit-val' : ''
          }`}
        ></div>
      </div>

      {isOpen && (
        <div
          className={`color-picker__panel`}
          ref={popover}
        >
          <RgbaStringColorPicker
            color={getColorInRgb(color)}
            onChange={onChange}
            className='rgba-string-color-picker'
          />
          <HexColorInput
            className='hex-color-input'
            color={getColorInHex(color)}
            onChange={onChange}
            prefixed
            alpha
          />

          <div className='color-picker__panel__preset-btns'>
            {WYSIWYG_COLORS.map((presetColor, i) => (
              <button
                key={i}
                className={`color-picker__panel__preset-btns__btn  ${
                  getColorInRgb(color) == getColorInRgb(presetColor)
                    ? 'color-picker__panel__preset-btns__btn--active border-eSecondary'
                    : ''
                }`}
                style={{
                  background: presetColor,
                }}
                onClick={() => onChange(presetColor)}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
