import { SendOutlined } from "@ant-design/icons";
import { Button, Space, Statistic, theme } from "antd";
import { useState } from "react";

type ReportButtonProps = {
    buttonRef?: React.Ref<HTMLElement>;
    /** 过期时间 */
    expireTime?: string;
    /** 显示图标 */
    showIcon?: boolean;
    /** 上报回调 */
    onSubmit: () => Promise<void>;
    /** 计时结束回调 */
    onTimerFinish?: () => void;
}

/** 上报按钮 */
const ReportButton: React.FC<ReportButtonProps> = ({ buttonRef, expireTime, showIcon, onSubmit, onTimerFinish }) => {
    const { token } = theme.useToken();
    const [loading, setLoading] = useState(false);
    const [disabled, setDisabled] = useState(true);

    const handleSubmit = async () => {
        setLoading(true);
        try {
            await onSubmit();
        }
        catch { }
        setLoading(false);
    }

    return (
        <Space>
            <Statistic.Countdown
                value={expireTime}
                format="D 天 HH 时 mm 分 ss 秒"
                valueStyle={{ color: token.colorError }}
                onFinish={() => {
                    setDisabled(true);
                    onTimerFinish?.();
                }}
                onChange={() => setDisabled(false)}
            />
            <Button
                ref={buttonRef}
                type="primary"
                loading={loading}
                disabled={loading || disabled}
                icon={showIcon ? <SendOutlined /> : null}
                onClick={handleSubmit}
            >立即上报</Button>
        </Space>
    );
}

export default ReportButton;
