import React, { useRef, useState }          from 'react';
import { ChromePicker, Color, ColorResult } from 'react-color';
import isEmpty                              from 'lodash-es/isEmpty';
import { ColorSelectorButton, Container }   from './styles';
import { rgbaObjectToHexA } from './colorConverter';
import { useOnClickOutside } from '../../util/useOnClickOutside';
import { Wrapper } from '../wrapper/wrapper.component';

type ColorPickerProps = {
    // hexa
    color: string;
    onColorChange: (color: string) => void;
    disableAlpha?: boolean;
    disabled?:boolean
    buttonMargin?: 'sm' | 'md' | 'lg' | 'off' | 'xxs' | 'xs' | 'xl' | 'xxl',
    children?: JSX.Element | JSX.Element[],
};

type colorPickerDataParams = {
    color: Color;
    initiator: EventTarget;
};

export const ColorPicker = ({color = '#000', onColorChange, disableAlpha = false, disabled, buttonMargin, children}: ColorPickerProps) => {
    const [ colorPickerData, setColorPickerData ] = useState<colorPickerDataParams | null>(null);
    const pickerRef = useRef(null);

    const onChangeComplete = (color: ColorResult) => {
        onColorChange(rgbaObjectToHexA(color.rgb));
    };

    const ColorPickerComponent = (
        <Container ref={ pickerRef }>
            <ChromePicker
                color={ color }
                onChangeComplete={ onChangeComplete }
                disableAlpha={ disableAlpha }
            />
        </Container>
    );

    const toggleColorPicker = (
        e: React.TouchEvent | React.MouseEvent
    ) => {
        if (!isEmpty(colorPickerData)) {
            setColorPickerData(null);
            return;
        }
        const colorPickerSettings = {
            color,
            initiator: e.target
        };
        setColorPickerData(colorPickerSettings);
    };

    const closeColorPicker = (e: Event) => {
        if (e.target === colorPickerData!.initiator) return;
        setColorPickerData(null);
    };

    useOnClickOutside(pickerRef, (e: Event) => closeColorPicker(e));

    return (
        <Wrapper maxWidth="fit-content" row>
            { children ? <span onClick={ toggleColorPicker }>{ children }</span> : (
                <Wrapper
                    style={ {
                        backgroundColor: '#fff',
                        borderRadius:    '50%',
                        cursor:          'pointer'
                    } }
                    maxWidth="fit-content"
                    margin={ buttonMargin }
                >
                    <ColorSelectorButton
                        color={ color }
                        onClick={ (e) => !disabled && toggleColorPicker(e) }
                    />
                </Wrapper>
            ) }
            { colorPickerData && (ColorPickerComponent) }
        </Wrapper>
    );
};
