import * as React from 'react';
import clsx from 'clsx';
import plugin from 'tailwindcss/plugin';

export type ColorPickerDerivedElement = HTMLInputElement;

export interface ColorPickerProps extends Omit<React.HTMLProps<ColorPickerDerivedElement>, 'size' | 'type' | 'label'> {
  square?: boolean;
  size?: 'small' | 'medium' | 'large';
}

export const colorPickerPlugin = plugin(({ addComponents }) => {
  addComponents({
    '.color-picker': {
      '&::-webkit-color-swatch-wrapper': {
        'padding': '0',
      },
      '&::-webkit-color-swatch': {
        'border': '2px solid black',
      },
      '&::-moz-color-swatch': {
        'border': '2px solid black',
      },
    },
  });
});

export const ColorPicker = React.forwardRef<
  ColorPickerDerivedElement,
  ColorPickerProps
>((
  {
    className,
    id: idProp,
    style,
    square = false,
    size = 'medium' as const,
    ...etcProps
  },
  forwardedRef,
) => {
  return (
    <div
      className={clsx(
        'inline-block align-center relative',
        {
          'w-4': square && size === 'small',
          'w-6': square && size === 'medium',
          'w-8': square && size === 'large',
        },
        {
          'w-8': !square && size === 'small',
          'w-12': !square && size === 'medium',
          'w-16': !square && size === 'large',
        },
        className,
      )}
      style={style}
    >
      <span
        className={clsx(
          'block w-full',
          {
            'p-[50%]': square,
            'p-[25%]': !square,
          },
        )}
      >
        {/*  todo add chevron down to picker */}
        <input
          {...etcProps}
          className={clsx(
            'color-picker absolute top-0 left-0 w-full h-full overflow-hidden ring-secondary/50 rounded cursor-pointer',
            'border-2 border-primary focus:border-secondary active:border-tertiary disabled:border-primary',
            'focus:outline-0 focus:ring-4',
            'active:ring-tertiary/50',
            'disabled:opacity-50 disabled:cursor-not-allowed',
          )}
          ref={forwardedRef}
          id={idProp}
          type="color"
        />
      </span>
    </div>
  );
});

ColorPicker.displayName = 'ColorPicker';

ColorPicker.defaultProps = {
  square: false as const,
  size: 'medium' as const,
};
