import React, { useEffect } from "react";
import { useSwitchChain } from "wagmi";

import { useToast } from "@providers/ToastProvider";
import { getCommonErrors } from "@utils/getCommonErrors";
import { useMappedChainData } from "../../hooks/useMappedChainData";
import { Button } from "./Button";

export const SwitchChain = ({ switchTo }: { switchTo: number }) => {
	const mappedChainData = useMappedChainData();
	const { switchChain, isPending, isError, error } = useSwitchChain();
	const { showToast } = useToast();

	function getButtonLabel() {
		if (isPending) return "Confirm in wallet";

		// biome-ignore format:
		return `Switch to ${mappedChainData?.[switchTo]?.name} network`;
	}

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (isError) {
			const { name, shortMessage } = getCommonErrors(error);
			showToast(name, shortMessage, "error");
		}
	}, [isError]);

	return (
		<Button
			label={getButtonLabel()}
			onClick={() => switchChain({ chainId: switchTo })}
			isLoading={isPending}
			disabled={isPending}
		/>
	);
};
