import { observer } from "mobx-react";
import { ObservableReactComponent } from "../../../../ObservableReactComponent";
import { Conditional } from "../Backend/TemplateManager";
import { action, makeObservable, observable, runInAction } from "mobx";
import React from "react";

interface ConditionalsTextAreaProps {
    conditional: Conditional;
    property: keyof Conditional;
}

@observer
export class ConditionalsTextArea extends ObservableReactComponent<ConditionalsTextAreaProps> {

    private mirrorRef: HTMLSpanElement | null = null;

    @observable private inputWidth: string = '60px';

    constructor(props: ConditionalsTextAreaProps) {
        super(props);
        makeObservable(this);
    }

    setMirrorRef: React.LegacyRef<HTMLSpanElement> = (node) => { this.mirrorRef = node }

    @action updateInputWidth() {
        const mirror = this.mirrorRef;
        if (mirror) {
            const width = mirror.offsetWidth;
            if ( width + 8 > 60) this.inputWidth = `${width + 8}px`;
        }
    }

    render() {
        return (
            <div style={{ display: 'inline-block', position: 'relative' }}>
                <span
                    ref={this.setMirrorRef}
                    style={{
                        position: 'absolute',
                        visibility: 'hidden',
                        whiteSpace: 'pre',
                        font: 'inherit',
                        padding: 0,
                    }}
                >
                    {this._props.conditional[this._props.property] || ' '}
                </span>
                <input
                    className="form-row-input"
                    value={this.props.conditional[this.props.property] ?? ''}
                    onChange={e => {
                        runInAction(() => {
                        this.props.conditional[this.props.property] = e.target.value as "=" | ">" | "<" | "contains";
                        });
                        this.updateInputWidth();
                    }}
                    style={{ width: this.inputWidth }}
                    placeholder={this.props.property}
                />
            </div>
        );
    }

}