import React from 'react';

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

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' | 'freehand' | 'watermark';
  isCollapse: boolean;
  pickerToggle: (e?: React.MouseEvent<HTMLElement>) => void;
  throughPortal: boolean;
};

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

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

  let ColorPickerGenerator = (
    <PickerContainer>
      <Blanket onMouseDown={pickerToggle} />
      <ColorPicker
        color={selectedColor}
        onSubmit={(color: any): void => {
          pickerToggle();
          onClick(color.hex);
        }}
      />
    </PickerContainer>
  );

  if (throughPortal) {
    ColorPickerGenerator = <Portal>{ColorPickerGenerator}</Portal>;
  }

  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}
          selected={!colorList.find(ele => selectedColor === ele.color)}
        >
          <Icon glyph="color-picker" />
        </Item>
        {!isCollapse ? ColorPickerGenerator : null}
      </Group>
    </>
  );
};

export default ColorSelector;
