import { useState, useEffect } from "react";

import { Box, Typography, SvgIcon, useTheme } from "@mui/material";

import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormHelperText from '@mui/material/FormHelperText';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

import { isNetworkAvailable } from "../../constants";
import EthIcon from "../../assets/tokens/ETH.svg?react";

import { useSwitchChain } from 'wagmi';
import toast from "react-hot-toast";

function SelectNetwork({ chainId, wrongNetworkToastId, setWrongNetworkToastId }) {
    const theme = useTheme();
    const { chains, switchChain } = useSwitchChain();

    const [networkId, setNetworkId] = useState(chainId);

    useEffect(() => {
        if (chainId !== networkId) setNetworkId(chainId);
    }, [chainId])

    const handleChange = (event) => {
        const chainName = chains.find((chain) => chain.id === event.target.value).name;
        toast.dismiss(wrongNetworkToastId);
        const toastId = toast.loading(`Trying to connect to ${chainName} network... Wait please`, {
            position: 'bottom-right'
        });
        setWrongNetworkToastId(toastId);

        setNetworkId(event.target.value);
        switchChain({ chainId: event.target.value });
    }

    return(
        <FormControl sx={{ width: "155px" }}>
            <Select
                labelId="network-select-helper-label"
                id="network-select-helper"
                value={networkId}
                onChange={handleChange}
                sx={{
                    boxShadow: 'none',
                    '.MuiOutlinedInput-notchedOutline': {
                        borderColor: `${theme.colors.backgroundColor} !important`,
                    },
                    '.Mui-focused': {
                        border: `1px solid ${theme.colors.backgroundColor} !important`,
                    }
                }}
            >
                {chains.map(chain => {
                    return (
                        <MenuItem key={chain.name} value={chain.id}>
                            <Box gap="10px" display="flex" flexDirection="row" alignItems="center">
                                <SvgIcon component={EthIcon} viewBox="0 0 32 32" />
                                <Typography>{chain.name}</Typography>
                            </Box>
                        </MenuItem>
                    )
                })}
            </Select>
        </FormControl>
    )
}

export default SelectNetwork;
