import { useSelector } from "react-redux";

import type { FormattedQuoteResponse } from "@hooks/apis/common/quote/types";
import { isManualQuote } from "@hooks/apis/common/quote/useQuote";
import { useTheme } from "@hooks/useTheme";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { formatValue } from "@utils/formatValue";
import { getBorderRadius } from "@utils/getBorderRadius";
import { getTimeInMins } from "@utils/getTimeInMins";
import { NoGasTag } from "../NoGasTag";
import { Dot } from "./utils/Dot";
import { Fees } from "./utils/Fees";
import { RouteProtocol } from "./utils/RouteProtocol";
import { RouteTag, tagsInfo } from "./utils/RouteTag";

type RouteItemType = {
	route: FormattedQuoteResponse;
	onClick: () => void;
	isActive: boolean;
	tags?: Array<"best" | "fast">;
};

export const RouteItem = ({
	route,
	onClick,
	isActive,
	tags,
}: RouteItemType) => {
	const theme = useTheme();
	const locale = useSelector((state: ReduxStateType) => state.settings.language);
	// biome-ignore format:
	const style = `${isActive ? 'bn-bg-accent bn-border-theme' : 'bn-bg-layer-2 bn-border-transparent'} bn-border bn-border-solid bn-px-4 bn-py-2 bn-flex-1 bn-cursor-pointer bn-w-full`;

	const { primaryOutput, estimatedFulfilTime } = route;
	const toAmount = primaryOutput.amount;
	const toToken = primaryOutput.token;

	return (
		<button
			type="button"
			className={style}
			onClick={onClick}
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
		>
			{tags?.length ? (
				<div className="bn-flex bn-items-center bn-space-x-2 bn-mb-3 ">
					{tags.map((item) => (
						<RouteTag item={tagsInfo[item]} isActive={isActive} key={item} />
					))}
				</div>
			) : undefined}

			<div className="bn-space-y-2">
				{/* amount */}
				<div className="bn-aeonik-font bn-flex bn-space-y-1 bn-flex-col">
					<p className="bn-text-base bn-font-medium bn-text-primary bn-text-left bn-leading-[18px]">
						{adjustDecimals(formatValue(toAmount, toToken.decimals), 3, locale)}{" "}
						{toToken.symbol}
					</p>
					{primaryOutput?.valueInUsd && (
						<p className="bn-text-secondary bn-text-sm bn-text-left bn-leading-[14px]">
							${adjustDecimals(primaryOutput.valueInUsd, 2, locale)}
						</p>
					)}
				</div>

				{/* route info */}
				<div className="bn-flex bn-items-center bn-space-x-2 bn-text-secondary bn-text-sm">
					<RouteProtocol
						routeDetails={isManualQuote(route) ? route.protocol : undefined}
					/>
					<Dot />
					<span className="bn-aeonik-font">
						{getTimeInMins(estimatedFulfilTime).fullShort}
					</span>
					<Fees route={route} reverse />
				</div>
			</div>
		</button>
	);
};
