import React, { useState, useRef } from 'react'
import { createPortal } from 'react-dom'
import { ChromePicker } from 'react-color'
import { Button, Icon } from '$core-components'
import { t } from '$themelocalization'
import './ColorPicker.scss'

const colorList = ['#000000', '#ffffff', '#00AEEF', '#EC008C', '#E6E6E6', '#D2232A', '#41AD49', '#009F8A', '#CC68A9', '#F5A623']

const ColorPicker = ({ color, setColor, children, isShape }) => {
  const [showColorPicker, setShowColorPicker] = useState(false)
  const buttonRef = useRef(null)

  return <Button className="icon-btn" onClick={() => setShowColorPicker(true)} ref={buttonRef}>
    {children}
    {showColorPicker &&
      createPortal(
        <div className="color-section">
          <div className={`color-controls-title`}>{t('UEdit.ColorPicker.Title')}</div>
          <Button className="icon-btn uedit-close" onClick={(e) => {
            e.stopPropagation();
            setShowColorPicker(false)
          }}>
            <Icon name="uedit-close.svg" width="20px" height="20px"/>
          </Button>
          <ChromePicker
              disableAlpha={true}
              width={'100%'}
              color={color || '#000000'}
              onChangeComplete={(color) => setColor(color?.hex || '#000000')}
          />
          <div className="text-color">
            <div className={`recent-colors-title`}>{t('UEdit.ColorPicker.RecentColors')}</div>
            <div className="color-swatch">
              {isShape && <div key={'no-color'} className="color-swatch-icon no-color">
                <div className="color" style={{backgroundColor: "#FFF"}}
                     onClick={() => setColor(null)}/>
              </div>}
              {colorList.map((color, idx) => {
                return <div key={idx} className="color-swatch-icon">
                  <div className="color" style={{backgroundColor: color}}
                       onClick={() => setColor(color)}/>
                    </div>
                  },
              )}
            </div>
          </div>
        </div>
          , document.body)}
  </Button>


}

export default ColorPicker
