import { useState, useEffect, useRef } 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 { parseKnownToken } from "../../components/Token/Token";

import { useSwitchChain } from 'wagmi';
import { useNavigate, useLocation } from 'react-router-dom';
import toast from "react-hot-toast";

function SelectNetwork({ chainId, wrongNetworkToastId, setWrongNetworkToastId, small, status }) {
    const theme = useTheme();
    const navigate = useNavigate();
    const hasAttemptedSwitch = useRef(false);

    const { chains, switchChain } = useSwitchChain();
    const { pathname } = useLocation();

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

    useEffect(() => {
        if (status === 'reconnecting' || status === 'connecting') return;

        const parts = pathname.split('/');
        if (!hasAttemptedSwitch.current && parts.length > 2) {
            let targetChain = chains.at(0);
            const chainName = parts[1].toLowerCase();
            const chain = chains.find(chain => chain.name.toLowerCase() === chainName);
            if (chain && targetChain.name !== chain.name) {
                targetChain = chain;
            }

            hasAttemptedSwitch.current = true;
            changeNetworkId(targetChain.name, targetChain.id);
        }
    }, [status, chains, pathname]);

    const changeNetworkId = (chainName, newNetworkId) => {
        toast.dismiss(wrongNetworkToastId);
        const toastId = toast.loading(`Trying to connect to ${chainName} network... Wait please`, {
            position: 'bottom-right'
        });
        setWrongNetworkToastId(toastId);

        setNetworkId(newNetworkId);
        switchChain({
            chainId: newNetworkId
        }, {
            onSuccess: (data) => console.log("Network switched to", data.name),
            onError: (error) => console.log("Error during network switching", error),
        });
    }

    const handleChange = (event) => {
        const chainName = chains.find((chain) => chain.id === event.target.value).name;
        changeNetworkId(chainName, event.target.value);

        const parts = pathname.split('/');
        if (parts.length > 2) {
            parts[1] = chainName.toLowerCase();
            const newPath = parts.join("/");
            navigate(newPath, { replace: true });
        }
    }

    return(
        <FormControl sx={{ width: small ? "100px" : "155px" }}>
            <Select
                labelId="network-select-helper-label"
                id="network-select-helper"
                value={networkId}
                disabled={!hasAttemptedSwitch.current}
                onChange={handleChange}
                sx={{
                    boxShadow: 'none',
                    '.MuiOutlinedInput-notchedOutline': {
                        borderColor: `${theme.colors.backgroundColor} !important`,
                    },
                    '.Mui-focused': {
                        border: `1px solid ${theme.colors.backgroundColor} !important`,
                    }
                }}
            >
                {chains.map((chain, i) => {
                    return (
                        <MenuItem key={chain.name} value={chain.id}>
                            <Box gap="10px" display="flex" flexDirection="row" alignItems="center">
                                <SvgIcon sx={{ width: 22 }} component={parseKnownToken(chain?.nativeCurrency?.symbol)} inheritViewBox />
                                {!small && <Typography>{chain.name}</Typography>}
                            </Box>
                        </MenuItem>
                    )
                })}
            </Select>
        </FormControl>
    )
}

export default SelectNetwork;
