import { Button, SvgIcon, SwipeableDrawer, Typography } from "@mui/material";
import { styled, useTheme } from '@mui/material/styles';
import { useState } from "react";
import WalletIcon from "../../../assets/icons/wallet.svg?react";
import { useAccount, useConnect, injected } from "wagmi";
import toast from "react-hot-toast";

import InitialWalletView from "./InitialWalletView";

const WalletButton = ({ openWallet, connect }) => {
    const { isConnected, chain } = useAccount();
    const theme = useTheme();
    const onClick = isConnected ? openWallet : connect;
    const label = isConnected ? "Wallet" : `Connect`;
    return (
        <Button
            id="fatso-menu-button"
            variant="text"
            size="large"
            color="secondary"
            onClick={() => onClick()}
        >
            <SvgIcon component={WalletIcon} style={{ marginRight: theme.spacing(1) }} />
            <Typography>{label}</Typography>
        </Button>
    );
};

const PREFIX = "WalletDrawer";

const classes = {
    drawer: `${PREFIX}-drawer`,
    drawerPaper: `${PREFIX}-drawerPaper`,
};

const StyledSwipeableDrawer = styled(SwipeableDrawer)(({ theme }) => ({
    [`& .${classes.drawer}`]: {
        [theme.breakpoints.up("md")]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },

    [`& .${classes.drawerPaper}`]: {
        width: drawerWidth,
        borderRight: 0,
    },
}));

const drawerWidth = 360;

export function Wallet({ address, chainId, connect }) {
    const [isWalletOpen, setWalletOpen] = useState(false);
    const closeWallet = () => setWalletOpen(false);
    const openWallet = () => setWalletOpen(true);

    // only enable backdrop transition on ios devices,
    // because we can assume IOS is hosted on hight-end devices and will not drop frames
    // also disable discovery on IOS, because of it's 'swipe to go back' feat
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);

    return (
        <>
            <WalletButton connect={connect} openWallet={openWallet} />
            <StyledSwipeableDrawer
                disableBackdropTransition={!isIOS}
                disableDiscovery={isIOS}
                anchor="right"
                classes={{
                    paper: classes.drawerPaper,
                }}
                ModalProps={{
                    keepMounted: true, // Better open performance on mobile.
                }}
                open={isWalletOpen}
                onOpen={openWallet}
                onClose={closeWallet}
            >
                <InitialWalletView
                    isWalletOpen={isWalletOpen}
                    address={address}
                    chainId={chainId}
                    onClose={closeWallet}
                />
            </StyledSwipeableDrawer>
        </>
    );
}

export default Wallet;
