import { ColorPickerFieldDefinition } from "@insite/client-framework/Types/FieldDefinition";
import StandardControl from "@insite/shell-public/Components/StandardControl";
import { EditorTemplateProps } from "@insite/shell-public/EditorTemplateProps";
import ColorPicker from "@insite/shell/Components/Elements/ColorPicker";
import { colorResultToString } from "@insite/shell/Store/ShellSelectors";
import React from "react";
import { ColorResult } from "react-color";

export default class ColorPickerField extends React.Component<EditorTemplateProps<string, ColorPickerFieldDefinition>> {
    onChange = (color: ColorResult) => {
        const value = colorResultToString(color);
        this.props.updateField(this.props.fieldDefinition.name, value ?? "");
    };

    render() {
        return (
            <StandardControl
                fieldDefinition={this.props.fieldDefinition}
                labelId={`color-picker-${this.props.fieldDefinition.name}-label`}
            >
                <ColorPicker
                    id={`color-picker-${this.props.fieldDefinition.name}`}
                    color={this.props.fieldValue}
                    onChange={this.onChange}
                    popoverProps={{
                        positionFunction: (element: React.RefObject<HTMLUListElement | null>) => {
                            const top = element.current?.getBoundingClientRect()!.top || 0;
                            const height = 251;
                            return {
                                left: "35px",
                                top: this.props.fieldDefinition.popoverLocation === "top" ? top - height : top + 24,
                                position: "fixed",
                            };
                        },
                        zIndexKey: "shellPopover",
                    }}
                />
            </StandardControl>
        );
    }
}
