import Buttons from "@/components/basic/Buttons"
import { ButtonType } from "@/utils/types"
import { View } from "@tarojs/components"
import { useEffect, useState } from "react"

export default function Component(props: {
    onClick: Function,
    type?: ButtonType,
    lowLight?: boolean,
    title: string,
    btnStyle: any,
    lightLoading?: boolean
}) {
    //idle normal abnormal
    const [btnStatus, setBtnStatus] = useState('idle')
    const [timer, setTimer] = useState(null)

    useEffect(() => {
        if (btnStatus == 'normal') {
            var t = setTimeout(() => {
                setBtnStatus('abnormal')
            }, 500)
            setTimer(t as any)
        }
        else if (btnStatus == 'idle') {
            if (timer) {
                clearTimeout(timer)
            }
        }
        else if (btnStatus == 'abnormal') {
            setTimeout(() => {
                if (btnStatus == 'abnormal') {
                    setBtnStatus('idle')
                }
            }, 10000)
        }
    }, [btnStatus])

    function updateStatus(status) {
        setBtnStatus(status)
    }

    function click() {
        if (btnStatus != 'idle') {
            return;
        }
        if (global.postBtnUpdateStatus) {
            global.postBtnUpdateStatus('idle')
        }

        global.postBtnUpdateStatus = updateStatus;
        props.onClick();
    }

    return (
        <View style={{ opacity: btnStatus == 'idle' ? 1 : 0.4 }}>
            <Buttons title={props.title} type={props.type}
                lowLight={props.lowLight ? props.lowLight : false}
                onClick={click}
                disabled={btnStatus != 'idle'}
                showLoading={btnStatus == 'abnormal'}
                btnStyle={props.btnStyle}
                lightLoading={props.lightLoading}
            />
        </View>
    )
}