import React, { useState } from 'react';
import './ColorPicker.css';

const DEFAULT_PRESETS = ['#2F54EB','#1D39C4','#10239E','#CF1322','#8C5A00','#2E7D0A','#13C2C2','#722ED1',
  '#EB2F96','#8C5A00','#A0D911','#1890FF','#000000','#595959','#6E6E6E','#BFBFBF'];

export default function ColorPicker({ value = '#2F54EB', presets = DEFAULT_PRESETS, onChange }) {
  const [hex, setHex] = useState(value);
  const [alpha, setAlpha] = useState(1);

  const n = parseInt(hex.slice(1), 16);
  const preview = `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`;

  function emit(nextHex, nextAlpha) {
    onChange && onChange({ hex: nextHex, alpha: nextAlpha });
  }
  function onHexInput(e) {
    const v = e.target.value;
    if (/^#[0-9a-fA-F]{6}$/.test(v)) { setHex(v); emit(v, alpha); }
  }

  return (
    <div className="kole-colorpicker">
      <div className="kole-colorpicker-presets">
        {presets.map((c, i) => (
          <div
            key={i}
            className={'kole-colorpicker-swatch' + (c.toLowerCase() === hex.toLowerCase() ? ' is-active' : '')}
            style={{ background: c }}
            onClick={() => { setHex(c); emit(c, alpha); }}
          />
        ))}
      </div>
      <div className="kole-colorpicker-row">
        <div className="kole-colorpicker-preview" style={{ background: preview }} />
        <input type="color" className="kole-colorpicker-native" value={hex} onChange={e => { setHex(e.target.value); emit(e.target.value, alpha); }} />
        <input className="kole-colorpicker-hex" value={hex.toUpperCase()} maxLength={7} onChange={onHexInput} />
      </div>
      <div className="kole-colorpicker-alpha">
        透明度
        <input type="range" min="0" max="100" value={Math.round(alpha * 100)} onChange={e => { setAlpha(e.target.value / 100); emit(hex, e.target.value / 100); }} />
        <span>{Math.round(alpha * 100)}%</span>
      </div>
    </div>
  );
}
