import * as React from "react";
import { ChromePicker } from "react-color";
import { observer } from "mobx-react";

import * as theme from "./ColorCell.scss";

const COLOR_PICKER_HEIGHT = 224; // px
const COLOR_PICKER_WIDTH = 225; // px

export const ColorCell = observer(function ColorCell({ cell, row, column, onValueChanged } : any) {

    const selected = row.selected && column.selected;
    const edit = selected && !cell.isReadOnly;

    function renderEdit() {
        if (!edit || !cell.editing) {
            return null;
        }

        const style = {
            transform: undefined,
            position: undefined
        };

        const el = cell.custom;
        if (el) {
            const spaceLeft = el.offsetParent.clientHeight - el.offsetTop - el.clientHeight;
            if (spaceLeft < COLOR_PICKER_HEIGHT) {
                style.transform = `translate(${el.clientWidth}px, -${COLOR_PICKER_HEIGHT}px)`;
                style.position = "absolute";
            }
        }

        return (
            <div style={style}>
                <ChromePicker
                    disableAlpha={true}
                    color={cell.color}
                    onChangeComplete={handleChange}
                />
            </div>
        )
    }

    function setElement(e : HTMLElement) {
        if (e) {
            cell.custom = e;
        }
    }

    function handleChange(color) {
        if (onValueChanged && !cell.isReadOnly) {
            // onValueChanged(`rgba(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b}, ${color.rgb.a})`);
            onValueChanged(color.rgb);
        }
    }

    function renderView() {
        return <div style={{ background: cell.color }}/>;
    }

    const css = [
        (theme as any).typeColor,
        selected ? (theme as any).selected : null
    ].join(" ")
     .trim();

    return (
        <div className={css} ref={setElement}>
            {renderView()}
            {renderEdit()}
        </div>
    )
});
