import * as React from 'react';
import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { library } from '@fortawesome/fontawesome-svg-core';
import { faPalette } from '@fortawesome/free-solid-svg-icons/faPalette';
import { faChevronRight } from '@fortawesome/free-solid-svg-icons/faChevronRight';
import {
	blockStyle,
	outerDivStyle,
	colorWrapperStyle,
	colorNameStyle,
	colorSampleStyle,
	inputStyle,
	buttonStyle,
	pickerStyle
} from './colorPicker.style';
import { SketchPicker } from 'react-color';
import { Colors } from '../../models/colors';

library.add(faPalette);
library.add(faChevronRight);

interface ColorPickerProps {
	palette?: Colors;
	setColors?: (value: string, key: string) => any;
}

interface ColorPickerState {
	colors: {
		[key: string]: string;
	};
	showColors: boolean;
	openedColorPicker: number;
}

class ColorPicker extends React.PureComponent<ColorPickerProps, ColorPickerState> {
	constructor(props: ColorPickerProps) {
		super(props);
		this.state = {
			colors: this.props.palette,
			showColors: false,
			openedColorPicker: null
		};
	}

	render() {
		const handleColorPickerChangeComplete = (value: string, key: string) => {
			this.setState({ colors: Object.assign(this.state.colors, { [key]: value }) });

			if (/^#[0-9A-F]{6}$/i.test(value)) {
				this.props.setColors(value, key);
			}
		};

		const togglePicker = (index: number) => {
			this.setState(prevState => {
				const state = Object.assign({}, prevState, {
					openedColorPicker: index === prevState.openedColorPicker ? null : index
				});

				return state;
			});
		};

		return (
			<div className={outerDivStyle}>
				<button
					className={buttonStyle}
					onClick={() => this.setState({ showColors: !this.state.showColors })}
				>
					<FontAwesomeIcon icon="palette" />
					<FontAwesomeIcon icon="chevron-right" />
				</button>
				<div className={blockStyle(!this.state.showColors)}>
					{Object.keys(this.state.colors).map((color, i) => {
						return (
							<div className={colorWrapperStyle} key={i}>
								<div className={colorNameStyle}>{color}</div>
								<div
									className={colorSampleStyle(this.state.colors[color])}
									onClick={() => {
										togglePicker(i);
									}}
								/>
								{i === this.state.openedColorPicker && (
									<div className={pickerStyle}>
										<SketchPicker
											color={this.state.colors[color]}
											onChangeComplete={(value: any) => {
												handleColorPickerChangeComplete(value.hex, color);
											}}
										/>
									</div>
								)}
								<input
									className={inputStyle}
									type="text"
									value={this.state.colors[color]}
									readOnly
								/>
							</div>
						);
					})}
				</div>
			</div>
		);
	}
}

export default ColorPicker;
