import {Component, ChangeEvent, FocusEvent} from 'react'
import {StateOperation} from '@befe/brick-utils'

interface CustomInputState {
    customValue: StateOperation<string>
    hasFocus: StateOperation<boolean>
}

export class FeatureCustomInput {
    state: CustomInputState = {
        customValue: new StateOperation<string>(),
        hasFocus: new StateOperation<boolean>(),
    }

    opts!: {
        getValue: () => string
        onValueChange: (value: string) => void
    }

    hooks = {
        focus: () => {
            this.state.customValue.set(this.getValue())
            this.state.hasFocus.set(true)
        },
        blur: () => {
            this.state.hasFocus.set(false)
        },
        change: (e: ChangeEvent<HTMLInputElement> | FocusEvent<HTMLInputElement>) => {
            if (!this.state.hasFocus.get()) {
                this.state.hasFocus.set(true);
            }
            this.state.customValue.set(e.target.value)
            this.opts.onValueChange(e.target.value)
        },
    }

    constructor(
        comp: Component,
        propName: {
            customValue: string
            hasFocus: string
        },
        opts: FeatureCustomInput['opts']
    ) {
        this.state.customValue.setup(comp, propName.customValue)
        this.state.hasFocus.setup(comp, propName.hasFocus)

        this.opts = {
            getValue: opts.getValue,
            onValueChange: opts.onValueChange,
        }
    }

    getValue() {
        const {hasFocus, customValue} = this.state
        const {getValue} = this.opts
        if (hasFocus.get()) {
            return customValue.get()
        }
        return getValue()
    }
}
