import React from 'react';
import { ChromePicker } from 'react-color';

import Icon from '../Icon';
import Typography from '../Typography';

import {
  Group,
  Item,
  Circle,
  PickerContainer,
  Blanket,
} from '../../global/toolStyled';

import data from './data';

type Props = {
  title?: string;
  selectedColor?: string;
  onClick: (color: string) => void;
  mode?: 'normal' | 'shape' | 'watermark';
  isCollapse: boolean;
  pickerToggle: (e: React.MouseEvent<HTMLElement>) => void;
};

type ColorItem = {
  key: string | number | undefined;
  color: string;
  icon?: string;
};

const ColorSelector: React.FC<Props> = ({
  title = '',
  mode = 'normal',
  selectedColor = '',
  onClick,
  pickerToggle,
  isCollapse,
}: Props) => {
  const colorList: ColorItem[] = data[mode];

  return (
    <>
      {title ? (
        <Typography
          variant="subtitle"
          style={{ marginTop: '8px' }}
          align="left"
        >
          {title}
        </Typography>
      ) : null}
      <Group>
        {colorList.map((ele: ColorItem) => (
          <Item
            key={ele.key}
            selected={selectedColor === ele.color}
            onMouseDown={(): void => {
              onClick(ele.color);
            }}
          >
            {ele.icon ? (
              <Icon glyph={ele.icon} />
            ) : (
              <Circle color={ele.color} />
            )}
          </Item>
        ))}
        <Item onMouseDown={pickerToggle}>
          <Icon glyph="color-picker" />
        </Item>
        {!isCollapse ? (
          <PickerContainer>
            <Blanket onMouseDown={pickerToggle} />
            <ChromePicker
              color={selectedColor}
              disableAlpha
              onChange={(color: any, event: any): void => {
                event.preventDefault();
                onClick(color.hex);
              }}
            />
          </PickerContainer>
        ) : null}
      </Group>
    </>
  );
};

export default ColorSelector;
