import { useEffect, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";

import { ModalCloseBtn } from "@components/common/ModalHeader";
import { NewRouteItem } from "@components/common/RouteItem/NewRouteItem";
import {
	type FormattedQuoteResponse,
	ROUTE_TAG,
	type RouteTag,
} from "@hooks/apis/common/quote/types";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { useTopRoutes } from "@hooks/apis/common/quote/useTopRoutes";
import { isAutoQuote, isManualQuote } from "@hooks/apis/common/quote/utils";
import { setActiveRoute } from "@store/routesSlice";
import type { ReduxStateType } from "@store/types";
import { onSelectRoute, onViewRouteComparison } from "../../analytics/events";

export const CompareCard = ({ closePanel }: { closePanel: () => void }) => {
	const dispatch = useDispatch();
	const { auto, manual } = useTopRoutes();
	const routingMode = useSelector(
		(state: ReduxStateType) => state.settings.routingMode,
	);

	// Get top options based on routing mode
	const topOptions = useMemo(() => {
		const options: Array<{
			route: FormattedQuoteResponse;
			type: RouteTag | "DEFAULT";
		}> = [];

		if (routingMode === "auto") {
			// Auto mode: show suggestedRoute, maxOutputRoute, fastestRoute
			if (auto.suggestedRoute) {
				options.push({
					route: auto.suggestedRoute,
					type: ROUTE_TAG.SUGGESTED,
				});
			}
			if (auto.maxOutputRoute) {
				options.push({
					route: auto.maxOutputRoute,
					type: ROUTE_TAG.MAX_OUTPUT,
				});
			}
			if (auto.fastestRoute) {
				options.push({ route: auto.fastestRoute, type: ROUTE_TAG.FASTEST });
			}
		} else {
			// Manual mode: show maxOutputRoute, fastestRoute
			if (manual.maxOutputRoute) {
				options.push({
					route: manual.maxOutputRoute,
					type: ROUTE_TAG.MAX_OUTPUT,
				});
			}
			if (manual.fastestRoute) {
				options.push({ route: manual.fastestRoute, type: ROUTE_TAG.FASTEST });
			}
		}

		return options;
	}, [routingMode, auto, manual]);

	// Get other routes based on routing mode
	const otherRoutes = useMemo(() => {
		if (routingMode === "auto") {
			// Auto mode: no rest routes
			return [] as Array<{
				route: FormattedQuoteResponse;
				type: RouteTag | "DEFAULT";
			}>;
		}

		// Manual mode: get restRoutes
		const topRouteIds = new Set(
			topOptions.map((option) => option.route.quoteId),
		);

		return (manual.restRoutes || [])
			.filter((route) => !topRouteIds.has(route.quoteId))
			.map((route) => ({ route, type: "DEFAULT" as const }));
	}, [routingMode, topOptions, manual.restRoutes]);

	const { data: activeRoute } = useActiveRoute();

	useEffect(() => {
		onViewRouteComparison();
	}, []);

	const emitEvent = (route: FormattedQuoteResponse) => {
		const protocol = isManualQuote(route) ? route.protocol : undefined;

		onSelectRoute({
			provider_name: protocol?.dexDetails?.protocol.name ?? "",
			source_chain_id: route.primaryInput.token.chainId,
			destination_chain_id: route.primaryOutput.token.chainId,
			source_token_symbol: route.primaryInput.token.symbol,
			destination_token_symbol: route.primaryOutput.token.symbol,
			input_amount_usd: Number(route.primaryInput.amount),
			estimated_output_amount: Number(route.minOutput?.formattedAmount),
			estimated_time: route.estimatedFulfilTime,
			provider_best_output: Number(route.primaryOutput.amount),
			provider_name_best_output: protocol?.dexDetails?.amountOut,
			provider_best_time: route.estimatedFulfilTime,
		});
	};

	return (
		<div className="bn-flex bn-flex-col bn-h-full bn-overflow-hidden bn-pb-4">
			{/* Header - Fixed */}
			<div className="bn-flex-shrink-0 bn-px-5 bn-py-[14px] bn-relative bn-flex bn-items-center bn-justify-between bn-border-b bn-border-subtle bn-border-solid">
				<div>
					<p className="bn-text-left bn-text-primary bn-text-base bn-font-semibold bn-mb-1 bn-leading-[19.2px]">
						Browse Options
					</p>
					<p className="bn-text-sm bn-font-normal bn-text-secondary">
						Compare price and select preferred route
					</p>
				</div>
				<ModalCloseBtn closeModal={closePanel} />
			</div>

			{/* Content area - Flexible but not scrollable */}
			<div className="bn-flex-1 bn-flex bn-flex-col bn-overflow-hidden">
				{/* TOP OPTIONS Section - Fixed */}
				{topOptions.length > 0 && (
					<div className="bn-flex-shrink-0 bn-px-5 bn-py-3 bn-pb-6">
						<div className="bn-space-y-2">
							{topOptions.map(({ route, type }) => (
								<NewRouteItem
									key={route.quoteId}
									route={route}
									type={type}
									isActive={
										isAutoQuote(activeRoute)
											? isAutoQuote(route) &&
												activeRoute?.quoteId === route.quoteId
											: isManualQuote(activeRoute)
												? activeRoute?.quoteId === route.quoteId
												: false
									}
									onClick={() => {
										dispatch(setActiveRoute(route));
										emitEvent(route);
										closePanel();
									}}
									maxOutputRoute={
										routingMode === "auto"
											? auto.maxOutputRoute
											: manual.maxOutputRoute
									}
									selectedRoute={activeRoute}
								/>
							))}
						</div>
					</div>
				)}

				{/* OTHER BUNGEE ROUTES Section - Scrollable */}
				{otherRoutes.length > 0 && (
					<div className="bn-flex-1 bn-flex bn-flex-col bn-overflow-hidden">
						<div className="bn-flex-shrink-0 bn-px-5 bn-pt-3">
							<div className="bn-text-secondary bn-capitalize bn-text-sm bn-mb-2">
								<span>ALTERNATIVE ROUTES</span>
							</div>
						</div>
						<div className="bn-flex-1 bn-overflow-y-auto bn-px-5 bn-pb-3">
							<div className="bn-space-y-2">
								{otherRoutes.map(({ route, type }) => (
									<NewRouteItem
										key={route.quoteId}
										route={route}
										type={type}
										isActive={
											isManualQuote(activeRoute)
												? activeRoute?.quoteId === route.quoteId
												: false
										}
										onClick={() => {
											dispatch(setActiveRoute(route));
											emitEvent(route);
											closePanel();
										}}
										maxOutputRoute={manual.maxOutputRoute}
									/>
								))}
							</div>
						</div>
					</div>
				)}
			</div>
		</div>
	);
};
