import { useState, useEffect, useMemo } from "react";
import {
    Divider,
    Typography,
    TableContainer,
    Table,
    TableHead,
    TableBody,
    TableRow,
    TableCell,
    useMediaQuery,
} from "@mui/material";
import { isAddress, getAddress } from "@ethersproject/address";

import Modal from "../../components/Modal/Modal";
import SwapCard from "../../components/Swap/SwapCard";
import TokenStack from "../../components/TokenStack/TokenStack";

import { DecimalBigNumber } from "../../helpers/DecimalBigNumber";
import { formatNumber } from "../../helpers/";
import { useBalance, useTokenSymbol } from "../../hooks/tokens";
import { DAI_ADDRESSES, FTSO_ADDRESSES, STNK_ADDRESSES, GHST_ADDRESSES } from "../../constants/addresses";

const TokenModal = ({ chainId, account, listOpen, setListOpen, setTokenAddress }) => {
    const isSmallScreen = useMediaQuery("(max-width: 599px)");
    const isVerySmallScreen = useMediaQuery("(max-width: 425px)");

    const [address, setAddress] = useState("");
    const [userInput, setUserInput] = useState("");
    const [isAddressCorrect, setIsAddressCorrect] = useState(false);

    const setUsedAddress = (token) => {
        setTokenAddress(token.address);
        setListOpen(false);
    }

    const { symbol: searchSymbol } = useTokenSymbol(chainId, address);
    const { balance: searchBalance } = useBalance(chainId, address, account);

    const { balance: daiBalance } = useBalance(chainId, "GDAI", account);
    const { balance: ftsoBalance } = useBalance(chainId, "FTSO", account);
    const { balance: stnkBalance } = useBalance(chainId, "STNK", account);
    const { balance: ghstBalance } = useBalance(chainId, "GHST", account);

    const { symbol: daiSymbol } = useTokenSymbol(chainId, "GDAI");
    const { symbol: ftsoSymbol } = useTokenSymbol(chainId, "FTSO");
    const { symbol: stnkSymbol } = useTokenSymbol(chainId, "STNK");
    const { symbol: ghstSymbol } = useTokenSymbol(chainId, "GHST");

    const searchToken = useMemo(() => {
        return [{
            name: searchSymbol,
            icons: ["X"],
            balance: searchBalance,
            address: address
        }]
    }, [searchSymbol, searchBalance, address]);

    const knownTokens = useMemo(() => {
        return [
            {
                name: daiSymbol,
                icons: ["GDAI"],
                balance: daiBalance,
                address: DAI_ADDRESSES[chainId]
            },
            {
                name: ftsoSymbol,
                icons: ["FTSO"],
                balance: ftsoBalance,
                address: FTSO_ADDRESSES[chainId]
            },
            {
                name: stnkSymbol,
                icons: ["STNK"],
                balance: stnkBalance,
                address: STNK_ADDRESSES[chainId]
            },
            {
                name: ghstSymbol,
                icons: ["GHST"],
                balance: ghstBalance,
                address: GHST_ADDRESSES[chainId]
            }
        ]
    }, [daiSymbol, ftsoSymbol, stnkSymbol, ghstSymbol, daiBalance, ftsoBalance, stnkBalance, ghstBalance]);

    useEffect(() => {
        if (isAddress(userInput)) {
            setAddress(getAddress(userInput));
            setIsAddressCorrect(true);
        } else {
            setAddress("");
            setIsAddressCorrect(false);
        }
    }, [userInput])

    return (
        <Modal
            maxWidth="476px"
            minHeight="200px"
            open={listOpen}
            headerText={"Select a token"}
            onClose={() => setListOpen(false)}
        >
            <SwapCard
                placeholder="0x"
                inputType="string"
                inputFontSize="12px"
                inputWidth={isVerySmallScreen ? "210px" : isSmallScreen ? "340px" : "386px"}
                value={userInput}
                onChange={event => setUserInput(event.currentTarget.value)}
            />
            <Divider style={{ margin: "20px 0" }} />
            <Typography variant="h7">Token Name</Typography>
            <TableContainer sx={{ maxHeight: "260px" }}>
                <Table aria-label="Available tokens" style={{ tableLayout: "fixed" }}>
                    <TableHead sx={{ display: "" }}>
                        <TableRow>
                            <TableCell style={{ padding: "8px 0", width: "50px" }}></TableCell>
                            <TableCell style={{ padding: "8px 0", width: "100px" }}></TableCell>
                            <TableCell style={{ padding: "8px 0", width: "auto" }}></TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {(isAddressCorrect ? searchToken : knownTokens).map((token, index) => {
                            return (
                                <TableRow onClick={() => setUsedAddress(token)} hover key={index} id={index + `--token`} data-testid={index + `--token`}>
                                    <TableCell style={{ padding: "8px 0" }}>
                                        <TokenStack style={{ width: "32px", height: "32px" }} tokens={token.icons} />
                                    </TableCell>

                                    <TableCell style={{ padding: "8px 0", height: "32px" }}>
                                        <Typography>{token.name}</Typography>
                                    </TableCell>

                                    <TableCell style={{ display: "flex", justifyContent: "end" }}>
                                        <Typography>{formatNumber(token.balance, 5)}</Typography>
                                    </TableCell>
                                </TableRow>
                            )
                        })}
                    </TableBody>
                </Table>
            </TableContainer>

        </Modal>
    )
}

export default TokenModal;
