import { motion } from "framer-motion";
import { useSelector } from "react-redux";

import { useFetchQuote } from "@hooks/apis/useFetchQuote";
import { useFetchV2Quote } from "@hooks/apis/useFetchV2Quote";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { CompareButton } from "../Compare/CompareButton";
import { MIcon } from "../common/MIcon";

export const BestPrice = () => {
	const { data: autoSwapData } = useFetchQuote();
	const { formattedData: gatewayData } = useFetchV2Quote();
	const outputTokens = useSelector(
		(state: ReduxStateType) => state.quoteParams.toTokens,
	);
	const locale = useSelector((state: ReduxStateType) => state.settings.language);

	if (!autoSwapData || !gatewayData) return null;

	const { primaryOutput } = autoSwapData;

	const getDiffInOutput = () => {
		if (primaryOutput?.valueInUsd && gatewayData?.[0]) {
			return primaryOutput?.valueInUsd - gatewayData?.[0]?.receivedValueInUsd;
		}
		return 0;
	};

	if (getDiffInOutput() <= 0 || outputTokens?.length > 1) return null;

	return (
		<motion.div
			layout
			className="bn-px-4 bn-py-2 bn-flex bn-items-center bn-justify-between bn-bg-accent2 -bn-mt-[7px]"
		>
			<div className="bn-flex bn-items-center bn-space-x-1">
				<MIcon name="bolt" classNames="bn-text-base bn-text-accent2" />

				<div className="bn-text-sm bn-font-medium bn-aeonik-font bn-text-primary bn-flex bn-flex-wrap">
					<p className="bn-text-accent2 bn-pr-1">Best Price: </p>
					<p>Receive ${adjustDecimals(getDiffInOutput(), 2, locale)} more</p>
				</div>
			</div>
			<CompareButton />
		</motion.div>
	);
};
