import { useDispatch } from "react-redux";

import type { FormattedQuoteResponse } from "@hooks/apis/common/quote/types";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { useBestRoutes } from "@hooks/apis/common/quote/useBestRoutes";
import { setActiveRoute } from "@store/routesSlice";
import { areBothRoutesSame } from "@utils/areBothRoutesSame";
import { RouteItem } from ".";
import { ComparisonItem } from "./ComparisonItem";
import { RouteItemSkeleton } from "./utils/SkeletonLoader";

export const RoutesWrapper = () => {
	const { bestRoute, fastestRoute } = useBestRoutes();
	const { data: activeRoute, isRefetching } = useActiveRoute();
	const dispatch = useDispatch();

	if (!bestRoute || !fastestRoute) return null;

	function setRoute(route: FormattedQuoteResponse) {
		dispatch(setActiveRoute(route));
	}

	const isBestRouteActive = areBothRoutesSame(bestRoute, activeRoute);
	const isFastestRouteActive = areBothRoutesSame(fastestRoute, activeRoute);
	const neitherRoutesSelected = !isBestRouteActive && !isFastestRouteActive;

	return (
		<div className="bn-my-4 bn-w-full bn-space-x-2 bn-flex bn-items-start">
			{isRefetching ? (
				<>
					<RouteItemSkeleton />
					<RouteItemSkeleton />
				</>
			) : neitherRoutesSelected && activeRoute ? (
				<ComparisonItem
					route={activeRoute}
					isActive={true}
					onClick={() => {}}
					variant
				/>
			) : areBothRoutesSame(bestRoute, fastestRoute) ? (
				<ComparisonItem
					route={bestRoute}
					onClick={() => setRoute(bestRoute)}
					isActive={isBestRouteActive}
					tags={["best", "fast"]}
				/>
			) : (
				<>
					<RouteItem
						route={bestRoute}
						onClick={() => setRoute(bestRoute)}
						isActive={isBestRouteActive}
						tags={["best"]}
					/>
					<RouteItem
						route={fastestRoute}
						onClick={() => setRoute(fastestRoute)}
						isActive={isFastestRouteActive}
						tags={["fast"]}
					/>
				</>
			)}
		</div>
	);
};
