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

import { ReviewSection } from "@components/Review/ReviewSection";
import { ExchangeRate } from "@components/common/ExchangeRate";
import { MIcon } from "@components/common/MIcon";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { useTopRoutes } from "@hooks/apis/common/quote/useTopRoutes";
import { toggleCompareModal } from "@store/globalSlice";
import type { ReduxStateType } from "@store/types";

export const CompareButton = () => {
	const { data: activeRoute } = useActiveRoute();
	const dispatch = useDispatch();
	const routingMode = useSelector(
		(state: ReduxStateType) => state.settings.routingMode,
	);
	const { formattedAutoRoutes, auto, manual } = useTopRoutes();
	const [openDetails, setOpenDetails] = useState(false);

	// Check if there are any routes that are NOT top routes
	const hasNonTopRoutes = useMemo(() => {
		if (routingMode === "auto") {
			// For auto mode: check if there are routes not in the top routes set
			if (!formattedAutoRoutes?.length) return false;

			const topRouteIds = new Set(
				[auto.suggestedRoute, auto.maxOutputRoute, auto.fastestRoute]
					.filter((route): route is NonNullable<typeof route> => Boolean(route))
					.map((route) => route.quoteId),
			);

			// Check if any route in formattedAutoRoutes is not a top route
			return formattedAutoRoutes.some(
				(route) => !topRouteIds.has(route.quoteId),
			);
		}

		// For manual mode: check if there are rest routes (already filtered to exclude top routes)
		return (manual.restRoutes?.length ?? 0) > 0;
	}, [routingMode, formattedAutoRoutes, auto, manual]);

	if (!activeRoute) return null;

	const { srcToDestRate, destToSrcRate } = activeRoute;

	function openModal() {
		dispatch(toggleCompareModal(true));
	}

	return (
		<div>
			<div className="bn-flex bn-items-center bn-justify-between">
				<button
					type="button"
					onClick={() => setOpenDetails(!openDetails)}
					className="bn-text-secondary bn-text-sm bn-font-medium bn-flex bn-items-center"
				>
					Swap Details{" "}
					<MIcon
						name="keyboard_arrow_down"
						classNames="bn-text-xl bn-text-primary bn-ml-1"
					/>
				</button>

				{hasNonTopRoutes ? (
					<button
						type="button"
						onClick={openModal}
						className="bn-text-secondary bn-text-sm bn-font-normal bn-flex bn-items-center"
						id="view-all-routes-btn"
					>
						View All Routes{" "}
						<MIcon
							name="keyboard_arrow_right"
							classNames="bn-text-primary bn-ml-1 bn-text-xl"
						/>
					</button>
				) : srcToDestRate && destToSrcRate ? (
					<ExchangeRate />
				) : null}
			</div>

			{openDetails && (
				<div className="bn-mt-2">
					<ReviewSection />
				</div>
			)}
		</div>
	);
};
