import { useEffect, useState } from "react";

import { setActiveRoute } from "@store/routesSlice";
import { isWrapUnwrapCase } from "@utils/isWrapUnwrapCase";
import { useDispatch } from "react-redux";
import type {
	FormattedAutoQuote,
	FormattedManualQuote,
	FormattedQuoteResponse,
} from "./types";
import { useActiveRoute } from "./useActiveRoute";
import { useBestRoutes } from "./useBestRoutes";

/**
 * Route Selection Logic
 * If autoRoute is available and it's a wrap/unwrap case, set autoRoute as active route
 * If activeRoute not previously selected, set the best route as activeRoute
 *
 * If previous route is auto route, select the new auto route
 * If previous route is manual routes, select the new manual route (same bridge)
 * If the same manual route not found, set the best route as active route
 */

export const useQuote = () => {
	const dispatch = useDispatch();
	const [selectedRoute, setSelectedRoute] = useState<FormattedQuoteResponse>();
	const { bestRoute, autoRoute, manualRoutes } = useBestRoutes();
	const { data: activeRoute } = useActiveRoute();

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (autoRoute && isWrapUnwrapCase(autoRoute)) {
			setSelectedRoute(autoRoute);
		} else if (!activeRoute) {
			setSelectedRoute(bestRoute);
		} else {
			if (isAutoQuote(activeRoute)) {
				setSelectedRoute(autoRoute);
			} else {
				const filteredManualRoute = manualRoutes?.find(
					(route) => route.protocol.name === activeRoute.protocol.name,
				);
				setSelectedRoute(filteredManualRoute || bestRoute);
			}
		}
	}, [bestRoute]);

	useEffect(() => {
		if (dispatch) {
			dispatch(setActiveRoute(selectedRoute));
		}
	}, [selectedRoute, dispatch]);
};

// Check the routingMode to determine the type of route
export const isAutoQuote = (
	route: FormattedQuoteResponse | undefined | null,
): route is FormattedAutoQuote => route?.routingMode === "auto";

export const isManualQuote = (
	route: FormattedQuoteResponse | undefined | null,
): route is FormattedManualQuote => route?.routingMode === "manual";
