import { IconButton, Size, Type } from 'browndash-components';
import { IReactionDisposer, action, makeObservable, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { SettingsManager } from '../../../util/SettingsManager';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import './CollectionFreeFormView.scss';

/**
 * An Fsa Arc.  The first array element is a test condition function that will be observed.
 * The second array element is a function that will be invoked when the first test function
 * returns a truthy value
 */
// eslint-disable-next-line no-use-before-define
export type infoArc = [() => any, (res?: any) => infoState];

export const StateMessage = Symbol('StateMessage');
export const StateMessageGIF = Symbol('StateMessageGIF');
export const StateEntryFunc = Symbol('StateEntryFunc');
export class infoState {
    [StateMessage]: string = '';
    [StateMessageGIF]?: string = '';
    [StateEntryFunc]?: () => any;
    [key: string]: infoArc;
    constructor(message: string, arcs: { [key: string]: infoArc }, messageGif?: string, entryFunc?: () => any) {
        this[StateMessage] = message;
        Object.assign(this, arcs);
        this[StateMessageGIF] = messageGif;
        this[StateEntryFunc] = entryFunc;
    }
}

/**
 * Create an FSA state.
 * @param msg the message displayed when in this state
 * @param arcs an object with fields containing @infoArcs (an object with field names indicating the arc transition and
 * field values being a tuple of an arc transition trigger function (that returns a truthy value when the arc should fire),
 * and an arc transition action function (that sets the next state)
 * @param gif the gif displayed when in this state
 * @param entryFunc a function to call when entering the state
 * @returns an FSA state
 */
export function InfoState(
    msg: string, //
    arcs: { [key: string]: infoArc },
    gif?: string,
    entryFunc?: () => any
) {
    // eslint-disable-next-line new-cap
    return new infoState(msg, arcs, gif, entryFunc);
}

export interface CollectionFreeFormInfoStateProps {
    infoState: infoState;
    next: (state: infoState) => any;
    close: () => void;
}

@observer
export class CollectionFreeFormInfoState extends ObservableReactComponent<CollectionFreeFormInfoStateProps> {
    _disposers: IReactionDisposer[] = [];
    @observable _expanded = false;

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

    get State() {
        return this._props.infoState;
    }
    get Arcs() {
        return Object.keys(this.State ?? []).map(key => this.State?.[key]);
    }

    clearState = () => this._disposers.map(disposer => disposer());
    initState = () => {
        this._disposers = this.Arcs
            .map(arc => ({ test: arc[0], act: arc[1] }))
            .map(arc => reaction(
                    arc.test,
                    res => res && this._props.next(arc.act(res)),
                    { fireImmediately: true }
                )
        )}; // prettier-ignore

    componentDidMount() {
        this.initState();
    }
    componentDidUpdate(prevProps: Readonly<CollectionFreeFormInfoStateProps>) {
        super.componentDidUpdate(prevProps);
        this.clearState();
        this.initState();
    }
    componentWillUnmount() {
        this.clearState();
    }

    render() {
        const gif = this.State?.[StateMessageGIF];
        return (
            <div className="collectionFreeform-infoUI">
                <p className="collectionFreeform-infoUI-msg">
                    {this.State?.[StateMessage]}
                    <button
                        type="button"
                        className={'collectionFreeform-' + (!gif ? 'hidden' : 'infoUI-button')}
                        onClick={action(() => {
                            this._expanded = !this._expanded;
                        })}>
                        {this._expanded ? 'Less...' : 'More...'}
                    </button>
                </p>
                <div className={'collectionFreeform-' + (!this._expanded || !gif ? 'hidden' : 'infoUI-gif-container')}>
                    <img src={`/assets/${gif}`} alt="state message gif" />
                </div>
                <div className="collectionFreeform-infoUI-close">
                    <IconButton icon="x" color={SettingsManager.userColor} size={Size.XSMALL} type={Type.TERT} background={SettingsManager.userBackgroundColor} onClick={action(() => this.props.close())} />
                </div>
            </div>
        );
    }
}
