import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";

import { MIcon } from "@components/common/MIcon";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { useAccounts } from "@hooks/useAccounts";
import { toggleRecipientModal } from "@store/globalSlice";
import { setReceiverAddress } from "@store/quoteParamSlice";
import type { ReduxStateType } from "@store/types";
import { isWrapUnwrapCase } from "@utils/isWrapUnwrapCase";
import { replaceMetaMaskIcon } from "@utils/replaceMetaMask";
import { shortenAddress } from "@utils/shortenAddress";
import { AddOnItem } from "./AddOnItem";

export const RecipientAddress = () => {
	const dispatch = useDispatch();
	const { data: activeRoute } = useActiveRoute();
	const { receiver, receiverENS } = useSelector(
		(state: ReduxStateType) => state.quoteParams,
	);

	const { accounts } = useAccounts();

	const openRecipientModal = () => {
		dispatch(toggleRecipientModal(true));
	};

	const isReceiverAdded = Boolean(receiver);

	const label =
		isReceiverAdded && receiver
			? receiverENS || shortenAddress(receiver, 6)
			: "Recipient Address";

	// biome-ignore format:
	const actionItemStyle = isReceiverAdded
    ? "bn-text-theme bn-text-sm"
    : "bn-text-secondary bn-text-[20px]";
	// biome-ignore format:
	const actionItemIconName = isReceiverAdded ? "edit" : "add_circle";

	const disableRecipientAddress = !!isWrapUnwrapCase(activeRoute);

	const connectorIcon = accounts.find(
		(account) => account.address?.toLowerCase() === receiver?.toLowerCase(),
	)?.connector?.icon;

	const isCustomRecipient =
		!!receiver &&
		!accounts.find(
			(account) => account.address?.toLowerCase() === receiver?.toLowerCase(),
		);

	useEffect(() => {
		if (disableRecipientAddress) {
			dispatch(setReceiverAddress(""));
		}
	}, [disableRecipientAddress, dispatch]);

	return (
		<AddOnItem
			label={label}
			icon={
				connectorIcon ? (
					<img
						src={replaceMetaMaskIcon(connectorIcon)}
						alt="connector"
						className="bn-rounded-full bn-size-5 bn-mr-1"
					/>
				) : undefined
			}
			iconName="wallet"
			active={isReceiverAdded}
			actionItem={<MIcon classNames={actionItemStyle} name={actionItemIconName} />}
			onClick={disableRecipientAddress ? undefined : openRecipientModal}
			disabled={disableRecipientAddress}
			isCustomAddress={isCustomRecipient}
			className={isReceiverAdded ? "bn-aeonik-font" : undefined}
		/>
	);
};
