import { useState } from "react";
import { useDispatch } from "react-redux";

import { Button } from "@components/common/Button";
import { SquaredCheckbox } from "@components/common/SquaredCheckbox";
import { useToast } from "@providers/ToastProvider";
import { importToken } from "@store/globalSlice";
import {
	addOutputToken,
	setFromChainId,
	setFromTokens,
	setToChainId,
} from "@store/quoteParamSlice";
import { setTokenSelectorData } from "@store/tokenSelectorSlice";
import type { Token } from "../../Providers/ConfigProvider";
import { ImportTokenItem } from "./ImportTokenItem";

export const ImportToken = ({
	tokens,
	closePanel,
	isSourceTokenSelector,
}: {
	tokens: Token[];
	closePanel: () => void;
	isSourceTokenSelector: boolean;
}) => {
	const [addresses, setAddresses] = useState<string[]>([]);
	const [isDisclaimerChecked, setIsDisclaimerChecked] = useState<boolean>(false);
	const { showToast } = useToast();

	const dispatch = useDispatch();

	// @note: this is not optimized for tokens from multiple chains
	function dispatchImportedToken(values: string[]) {
		const _address = values[0];
		const _token = tokens.filter((token) => token.address === _address)[0];

		// Adding token to the localStorage
		dispatch(importToken({ token: _token }));

		// Adding the token to source/dest & closing the panels
		if (isSourceTokenSelector) {
			dispatch(setFromTokens(_token));
			dispatch(setFromChainId(_token.chainId));
		} else {
			dispatch(addOutputToken({ id: 0, token: _token }));
			dispatch(setToChainId(_token.chainId));
		}

		closePanel();
		dispatch(setTokenSelectorData({ isVisible: false }));
		// biome-ignore format:
		showToast("Token Imported Successfully", `${_token.symbol} has been added to your local storage`)
	}

	const handleClick = (token: Token) => {
		const newAddresses = addresses.slice(); // creating copy
		const isActive = newAddresses.includes(token.address);

		if (isActive) {
			const index = newAddresses.indexOf(token.address);
			newAddresses.splice(index, 1);
		} else {
			newAddresses.push(token.address);
		}

		setAddresses(newAddresses);
	};

	return (
		<div className="bn-p-4 bn-flex bn-flex-col bn-justify-between bn-h-full">
			<div>
				{tokens?.map((token) => {
					const _active = addresses.includes(token.address);

					return (
						<ImportTokenItem
							token={token}
							key={token.address}
							onClick={() => handleClick(token)}
							active={Boolean(_active)}
						/>
					);
				})}
			</div>

			<div>
				<div className="bn-flex bn-items-center bn-space-x-1.5 bn-mb-3">
					<SquaredCheckbox
						id="bungee-token-import-disclaimer"
						active={isDisclaimerChecked}
						setActive={setIsDisclaimerChecked}
						classNames="bn-border-2"
					/>
					<p className="bn-text-secondary bn-font-normal bn-text-sm">
						This token address is correct. By importing this token, I know and accept the
						risks.
					</p>
				</div>

				<Button
					label="Import Tokens"
					onClick={() => dispatchImportedToken(addresses)}
					disabled={!(addresses?.length > 0 && isDisclaimerChecked)}
				/>
			</div>
		</div>
	);
};
