import { useState } from "react";
import { useSelector } from "react-redux";

import type { Token } from "@/types/index";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { twMerge } from "@utils/tailwindMerge";
import { Tooltip } from "./Tooltip";

export const ExchangeRate = ({ classNames }: { classNames?: string }) => {
	const [showSrcRate, setShowSrcRate] = useState<boolean>(true);

	const style = twMerge(
		"bn-px-0 bn-aeonik-font bn-font-medium bn-text-sm bn-bg-transparent bn-border-0 bn-outline-0 bn-text-primary bn-cursor-pointer",
		classNames,
	);
	const { data: activeRoute } = useActiveRoute();

	if (!activeRoute) return null;

	const { srcToDestRate, destToSrcRate, input, output } = activeRoute;
	const inputToken = input[0].token;
	const outputToken = output[0].token;

	function getRate() {
		if (srcToDestRate && destToSrcRate) {
			if (showSrcRate)
				return (
					<Rate rate={srcToDestRate} tokenOne={inputToken} tokenTwo={outputToken} />
				);
			return (
				<Rate rate={destToSrcRate} tokenOne={outputToken} tokenTwo={inputToken} />
			);
		}
	}

	return (
		<button
			className={style}
			type="button"
			onClick={() => setShowSrcRate(!showSrcRate)}
		>
			{getRate()}
		</button>
	);
};

const Rate = ({
	rate,
	tokenOne,
	tokenTwo,
}: {
	rate: number;
	tokenOne: Token;
	tokenTwo: Token;
}) => {
	const locale = useSelector((state: ReduxStateType) => state.settings.language);

	const RateWithTooltip = () => (
		<Tooltip content={rate}>
			<div className="bn-mx-1 bn-inline-block bn-max-w-[60px] bn-overflow-hidden bn-text-ellipsis bn-whitespace-nowrap">
				{adjustDecimals(rate, 4, locale)}
			</div>
		</Tooltip>
	);

	return (
		<div className="bn-flex bn-items-center bn-space-x-1">
			1 {tokenOne.symbol} ~ <RateWithTooltip /> {tokenTwo.symbol}
		</div>
	);
};
