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

import { MIcon } from "@components/common/MIcon";
import { TokenIcon } from "@components/common/TokenIcon";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { useFetchQuotes } from "@hooks/apis/common/quote/useFetchQuotes";
import { toggleCompareModal } from "@store/globalSlice";
import { toggleSettingsModal } from "@store/settingsSlice";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { formatValue } from "@utils/formatValue";

export const CompareButton = () => {
	const { data: activeRoute } = useActiveRoute();
	const locale = useSelector((state: ReduxStateType) => state.settings.language);
	const dispatch = useDispatch();
	const { formattedAutoRoute, formattedManualRoutes } = useFetchQuotes();

	if (!activeRoute) return;

	const { primaryOutput, slippage } = activeRoute;
	function openModal() {
		dispatch(toggleCompareModal(true));
	}

	const multipleRoutes =
		(formattedManualRoutes && formattedManualRoutes?.length > 1) ||
		(formattedAutoRoute && formattedManualRoutes);

	const openSettings = () => {
		dispatch(toggleSettingsModal(true));
	};

	return (
		<div className="bn-flex bn-items-center bn-justify-between">
			<div className="bn-text-secondary bn-text-sm bn-flex bn-items-center">
				Min. Received:{" "}
				<div className="bn-flex bn-items-center bn-ml-1.5">
					<TokenIcon url={primaryOutput.token.logoURI} classNames="bn-w-4 bn-h-4" />
					<span className="bn-text-primary bn-font-medium bn-aeonik-font bn-pl-1">
						{adjustDecimals(
							formatValue(primaryOutput.minAmountOut, primaryOutput.token.decimals),
							3,
							locale,
						)}
					</span>
				</div>
			</div>

			{multipleRoutes ? (
				<button
					type="button"
					onClick={openModal}
					className="bn-text-secondary bn-text-sm bn-font-normal bn-flex bn-items-center"
					id="view-all-routes-btn"
				>
					View All Routes{" "}
					<MIcon name="keyboard_arrow_right" classNames="bn-text-primary bn-ml-1" />
				</button>
			) : (
				<div className="bn-text-secondary bn-text-sm bn-font-normal bn-flex bn-items-center bn-space-x-2">
					<p>
						Slippage: <span className="bn-text-primary bn-font-medium">{slippage}%</span>
					</p>
					<button className="bn-size-4" onClick={openSettings} type="button">
						<MIcon name="edit" classNames="bn-text-theme bn-text-base" />
					</button>
				</div>
			)}
		</div>
	);
};
