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

import { TokenIcon } from "@components/common/TokenIcon";
import { Tooltip } from "@components/common/Tooltip";
import type { FormattedRoute } from "@hooks/apis/useFetchV2Quote";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { getTimeInMins } from "@utils/getTimeInMins";

export const RouteItem = ({ route }: { route: FormattedRoute }) => {
	const locale = useSelector((state: ReduxStateType) => state.settings.language);

	return (
		<div className="bn-relative">
			<div className="bn-flex bn-justify-between bn-items-center bn-mb-4">
				<p className="bn-text-primary bn-text-sm bn-font-medium">
					{route.protocol.displayName || "Route"}{" "}
					<span className="bn-text-secondary bn-font-normal">
						~ {getTimeInMins(route.serviceTime).full}
					</span>
				</p>
				<p className="bn-text-primary bn-text-sm bn-font-medium bn-aeonik-font">
					${adjustDecimals(route.receivedValueInUsd, 2, locale)}
				</p>
			</div>
			<div className="bn-flex bn-justify-between bn-relative">
				{route.steps.map((step, index) => {
					return (
						<React.Fragment key={step.toAmount}>
							{index === 0 && <Icon url={step.fromToken.logoURI} />}
							<Tooltip
								content={
									typeof step.protocol === "string" ? "protocol" : step.protocol.displayName
								}
							>
								<div>
									<Icon
										url={typeof step.protocol === "string" ? step.protocol : step.protocol.icon}
									/>
								</div>
							</Tooltip>
							{index === route.steps.length - 1 && <Icon url={step.toToken.logoURI} />}
						</React.Fragment>
					);
				})}

				{/* dotted line */}
				<div className="bn-absolute bn-border-0 bn-border-b-2 bn-border-dashed bn-border-[#373A3E] bn-w-full bn-h-px bn-m-auto bn-top-0 bn-bottom-0" />
			</div>
		</div>
	);
};

const Icon = ({ url }: { url: string }) => {
	return (
		<TokenIcon
			url={url}
			classNames="bn-relative bn-z-10 bn-size-[30px] bn-border-[3px] bn-border-solid bn-border-primary"
		/>
	);
};
