import { useAccounts } from "@hooks/useAccounts";
import { useDispatch, useSelector } from "react-redux";
import { toggleRecipientModal } from "../../store/globalSlice";
import type { ReduxStateType } from "../../store/types";
import { shortenAddress } from "../../utils/shortenAddress";
import { MIcon } from "./MIcon";

export const AddRecipientButton = ({ receiver }: { receiver?: string }) => {
	const { accounts } = useAccounts();
	const dispatch = useDispatch();
	const openRecipientModal = () => {
		dispatch(toggleRecipientModal(true));
	};
	const _receiver = useSelector(
		(state: ReduxStateType) => state.quoteParams.receiver,
	);
	const receiverEns = useSelector(
		(state: ReduxStateType) => state.quoteParams.receiverENS,
	);
	const recieverAddress = receiver || _receiver;

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

	if (recieverAddress) {
		return (
			<div className="bn-flex bn-items-center bn-text-sm bn-font-medium bn-text-primary">
				{connectorIcon && (
					<img
						src={connectorIcon}
						alt="connector"
						className="bn-rounded-full bn-size-4 bn-mr-1"
					/>
				)}

				{receiverEns || shortenAddress(recieverAddress)}

				<button
					className="bn-ml-1.5 bn-bg-transparent bn-p-0 bn-border-0 bn-size-4 bn-cursor-pointer"
					type="button"
					onClick={openRecipientModal}
				>
					<MIcon name="edit" classNames="bn-text-theme bn-text-base" />
				</button>
			</div>
		);
	}
	return (
		<button
			type="button"
			className="bn-text-accent-1 bn-font-semibold bn-text-sm bn-bg-transparent bn-p-0 bn-border-0 bn-cursor-pointer bn-flex bn-items-center"
			onClick={openRecipientModal}
		>
			<MIcon name="wallet" classNames="bn-text-xl" />
			<span className="bn-pl-1">Add Address</span>
		</button>
	);
};
