import { useEffect, useState } from "react";

import { setActiveRoute } from "@store/routesSlice";
import { isWrapUnwrapCase } from "@utils/isWrapUnwrapCase";
import { useDispatch } from "react-redux";
import { onQuoteResult } from "../../../../analytics/events";
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, fastestRoute } = 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]);

	// biome-ignore lint/correctness/useExhaustiveDependencies: Wnen `selectedRoute` changes, it means `manualRoutes`, `fastestRoute` or `autoRoute` has changed
	useEffect(() => {
		if (dispatch) {
			dispatch(setActiveRoute(selectedRoute));
			// Emit event
			const quoteCount = [...(manualRoutes || []), autoRoute].filter(Boolean).length;

			onQuoteResult({
				bestoutput_option: bestRoute,
				fastest_option: fastestRoute,
				default_selected: selectedRoute,
				quote_count: quoteCount,
				status: quoteCount > 0 ? "success" : "no_quotes_returned",

				source_chain_id: selectedRoute?.primaryInput?.token?.chainId,
				destination_chain_id: selectedRoute?.primaryOutput?.token?.chainId,
				source_token_symbol: selectedRoute?.primaryInput?.token?.symbol,
				destination_token_symbol: selectedRoute?.primaryOutput?.token?.symbol,
				input_amount: selectedRoute?.primaryInput?.amount
					? Number(selectedRoute?.primaryInput?.amount)
					: undefined,
			});
		}
	}, [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";
