import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Paper } from "../../layout";
import { ListTile } from "../../listView/listTile";
import { Switch } from "../../switch";
import { useCallback, useContext, useMemo, useState } from "react";
import { AccountStatusEnum } from "@orderly.network/types";
import { StepItem } from "./sections/step";
import { useAccount, useCheckReferralCode, useGetReferralCode, useMutation } from "@orderly.network/hooks";
import Button from "../../button";
import { toast } from "../../toast";
import { RememberMe } from "./sections/rememberMe";
import { ReferralCode } from "./sections/referralCode";
import { OrderlyAppContext } from "../../provider";
export const WalletConnect = (props)=>{
    // const { status = AccountStatusEnum.NotConnected } = props;
    const { account, state: { status, isNew } } = useAccount();
    const [handleStep, setHandleStep] = useState(0);
    const [remember, setRemember] = useState(true);
    const localRefCode = localStorage.getItem("referral_code") || undefined;
    const [refCode, setRefCode] = useState(localRefCode);
    const [bindRefCode, { error: updateOrderError, isMutating: updateMutating }] = useMutation("/v1/referral/bind", "POST");
    const { referral } = useContext(OrderlyAppContext);
    const { isExist } = useCheckReferralCode(refCode);
    const { referral_code, isLoading: loadingReferralCode } = useGetReferralCode(account?.accountId);
    const buttonLabel = useMemo(()=>{
        if (status < AccountStatusEnum.SignedIn) {
            return "Sign in";
        }
        if (status < AccountStatusEnum.EnableTrading) {
            return "Enable Trading";
        }
        return "--";
    }, [
        status
    ]);
    const enableTrading = useCallback(()=>{
        setHandleStep(2);
        return props.onEnableTrading?.(remember).then(()=>{
            if (refCode && refCode.length > 0) {
                bindRefCode({
                    referral_code: refCode
                }).then((res)=>{
                    referral?.onBoundRefCode?.(true, undefined);
                }).catch((e)=>{
                    referral?.onBoundRefCode?.(false, e);
                }).finally(()=>{
                    localStorage.removeItem("referral_code");
                });
            }
            props.onComplete?.();
        }, (e)=>{
            let errorText = `${e}`;
            if ("message" in e) {
                errorText = e.message;
            }
            if ("referral code not exist" === errorText) {
                errorText = "This referral code does not exist";
            }
            toast.error(errorText);
        }).finally(()=>{
            setHandleStep(0);
        });
    }, [
        refCode
    ]);
    const onClick = useCallback(()=>{
        if (status < AccountStatusEnum.SignedIn) {
            setHandleStep(1);
            return props.onSignIn?.().finally(()=>{
                setHandleStep(0);
                // sign in success then auto enable trading
                enableTrading();
            });
        }
        if (status < AccountStatusEnum.EnableTrading) {
            return enableTrading();
        }
    }, [
        status,
        remember,
        refCode
    ]);
    const isExpired = status === AccountStatusEnum.DisabledTrading && !isNew;
    return /*#__PURE__*/ _jsxs("div", {
        id: "orderly-wallet-connect-view",
        children: [
            /*#__PURE__*/ _jsx("div", {
                className: "orderly-text-base-contrast-54 orderly-text-2xs orderly-py-4 desktop:orderly-text-base",
                children: isExpired ? "Your previous access has expired, you will receive a signature request to enable trading. Signing is free and will not send a transaction." : "Sign two requests to verify ownership of your wallet and enable trading. Signing is free."
            }),
            /*#__PURE__*/ _jsxs(Paper, {
                className: "orderly-bg-base-500",
                children: [
                    !isExpired && /*#__PURE__*/ _jsx(ListTile, {
                        className: "orderly-text-xs desktop:orderly-text-base",
                        avatar: /*#__PURE__*/ _jsx(StepItem, {
                            active: status <= AccountStatusEnum.NotSignedIn,
                            isLoading: handleStep === 1,
                            isCompleted: status >= AccountStatusEnum.SignedIn,
                            children: "1"
                        }),
                        title: "Sign in",
                        disabled: status < AccountStatusEnum.NotConnected || status >= AccountStatusEnum.SignedIn,
                        subtitle: "Confirm you own this wallet"
                    }),
                    /*#__PURE__*/ _jsx(ListTile, {
                        className: "orderly-text-xs desktop:orderly-text-base",
                        disabled: status < AccountStatusEnum.SignedIn,
                        avatar: /*#__PURE__*/ _jsx(StepItem, {
                            active: status >= AccountStatusEnum.SignedIn,
                            isLoading: handleStep === 2,
                            isCompleted: status >= AccountStatusEnum.EnableTrading,
                            children: isExpired ? 1 : 2
                        }),
                        title: "Enable Trading",
                        subtitle: "Enable secure access to our API for lightning-fast trading"
                    })
                ]
            }),
            (referral_code?.length || 0) === 0 && loadingReferralCode === false && /*#__PURE__*/ _jsx(ReferralCode, {
                className: "orderly-pt-5",
                refCode: refCode,
                setRefCode: setRefCode,
                isExist: isExist
            }),
            /*#__PURE__*/ _jsxs("div", {
                className: "orderly-py-4 orderly-flex orderly-justify-between orderly-items-center",
                children: [
                    /*#__PURE__*/ _jsx(RememberMe, {}),
                    /*#__PURE__*/ _jsx("div", {
                        children: /*#__PURE__*/ _jsx(Switch, {
                            id: "orderly-remember-me-switch",
                            checked: remember,
                            onCheckedChange: setRemember
                        })
                    })
                ]
            }),
            /*#__PURE__*/ _jsx("div", {
                children: /*#__PURE__*/ _jsx(Button, {
                    id: "orderly-wallet-connector-button",
                    className: "orderly-text-xs orderly-text-base-contrast",
                    fullWidth: true,
                    disabled: handleStep > 0 || isExist !== true && (refCode?.length || 0) > 0,
                    onClick: onClick,
                    loading: handleStep > 0,
                    children: buttonLabel
                })
            })
        ]
    });
};

//# sourceMappingURL=walletConnect.js.map