import { useEvent, useState } from 'functional-mini/component';
import { mountComponent } from '../../_util/component';
import { useComponentEvent } from '../../_util/hooks/useComponentEvent';
import useLayoutEffect from '../../_util/hooks/useLayoutEffect';
import { hasValue, useMergedState } from '../../_util/hooks/useMergedState';
import { triggerRefEvent } from '../../_util/hooks/useReportRef';
import { TextareaFunctionalProps } from './props';
var Textarea = function (props) {
    var isControlled = hasValue(props.controlled)
        ? !!props.controlled
        : hasValue(props.value);
    var option = {
        value: props.value,
    };
    if (!isControlled && hasValue(props.value)) {
        option = {
            defaultValue: props.value,
        };
    }
    var _a = useMergedState(props.defaultValue, option), value = _a[0], updateValue = _a[1];
    var _b = useState(false), selfFocus = _b[0], setSelfFocus = _b[1];
    var triggerEvent = useComponentEvent(props).triggerEvent;
    triggerRefEvent();
    useLayoutEffect(function (mount) {
        if (!isControlled && !mount) {
            updateValue(props.value);
        }
    }, [props.value]);
    useEvent('onChange', function (e) {
        var newValue = e.detail.value;
        if (!isControlled) {
            updateValue(newValue);
        }
        else {
        }
        triggerEvent('change', newValue, e);
    });
    useEvent('onFocus', function (e) {
        var newValue = e.detail.value;
        setSelfFocus(true);
        triggerEvent('focus', newValue, e);
    });
    useEvent('onBlur', function (e) {
        var newValue = e.detail.value;
        setSelfFocus(false);
        triggerEvent('blur', newValue, e);
    });
    useEvent('onConfirm', function (e) {
        var newValue = e.detail.value;
        triggerEvent('confirm', newValue, e);
    });
    useEvent('onClear', function (e) {
        if (!isControlled) {
            updateValue('');
        }
        triggerEvent('change', '', e);
    });
    useEvent('update', function (e) {
        if (isControlled) {
            return;
        }
        updateValue(e);
    });
    return {
        state: {
            value: value,
            controlled: isControlled,
        },
        selfFocus: selfFocus,
    };
};
mountComponent(Textarea, TextareaFunctionalProps);