import type { ReduxStateType } from "@store/types";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";

import { Button } from "@components/common/Button";
import { ModalCloseBtn } from "@components/common/ModalHeader";
import { Rewards } from "@components/common/Rewards";
import { useFetchQuotes } from "@hooks/apis/common/quote/useFetchQuotes";
import { useMappedChainData } from "@hooks/useMappedChainData";
import { ScreenTab, setScreenTab } from "@store/globalSlice";
import {
	addOutputToken,
	setAmount,
	setFromChainId,
	setFromTokens,
	setIsFetchingDisabled,
	setToChainId,
} from "@store/quoteParamSlice";
import { setSlippage } from "@store/settingsSlice";
import { NATIVE_TOKEN_ADDRESS } from "@utils/constants";
import { getOrderStatus } from "@utils/getOrderStatus";
import type { InflightInfo } from "../common/data";
import { getSubtitle, getTitle } from "../common/utils";
import { FAQ } from "./FAQ";
import { InflightBanner } from "./InFlightBanner";
import { InfoSection } from "./InfoSection";
import { RotatingText } from "./RotatingText";
import { Share } from "./Share";

export const InFlightLayout = ({ data }: { data: InflightInfo }) => {
	const dispatch = useDispatch();
	const [isFaqOpen, toggleFaq] = useState<boolean>(false);
	const [isShareOpen, toggleShare] = useState<boolean>(false);
	const paramAmount = useSelector(
		(state: ReduxStateType) => state.quoteParams.amounts,
	);
	const mappedChainData = useMappedChainData();

	const { refetch } = useFetchQuotes();

	const {
		swapTime,
		statusCode,
		input,
		output,
		primaryInput,
		primaryOutput,
		srcTimestamp,
		requestHash,
		routingMode,
		// fix this
		// rebateDetails,
	} = data.info;
	const { isCompleted, isExpired } = getOrderStatus(statusCode);

	/** timestamp could be either swap time in seconds or unix timestamp */
	const [timestamp, setTimestamp] = useState<number>(
		Math.floor(Date.now() / 1000),
	);

	// biome-ignore lint/correctness/useExhaustiveDependencies: tracking data.info instead of individual variables
	useEffect(() => {
		if (routingMode === "auto") {
			if (isCompleted) setTimestamp(swapTime);
			else setTimestamp(srcTimestamp);
		} else {
			setTimestamp(
				data.info.estimatedFulfilTime,
			); /** this needs to be replaced with swap time  */
		}
	}, [data.info, isCompleted]);

	const inputChainName = mappedChainData?.[primaryInput.token.chainId].name ?? "";
	const outputChainName =
		mappedChainData?.[primaryOutput.token.chainId].name ?? "";

	const duneLinks = {
		146:
			"https://dune.com/socketprotocol/bungee-aave-x-rings-x-sonic-scusd-campaign",
		5000:
			"https://dune.com/socketprotocol/bungee-protocol-x-meth-protocol-campaign-on-mantle-network",
	};
	const currentDuneLink =
		primaryOutput.token.chainId === 146 || primaryOutput.token.chainId === 5000
			? duneLinks?.[primaryOutput.token.chainId]
			: undefined;

	// resetting slippage
	// setting quote params based on current route
	function retry() {
		dispatch(setSlippage("dynamic"));
		dispatch(setFromChainId(primaryInput.token.chainId));
		dispatch(setToChainId(primaryOutput.token.chainId));
		dispatch(setFromTokens(primaryInput.token));
		dispatch(addOutputToken({ id: 0, token: primaryOutput.token }));
		dispatch(setAmount(primaryInput.amount));
		dispatch(setScreenTab(ScreenTab.HOME));
	}

	const isGasless =
		routingMode === "auto" &&
		primaryInput.token.address.toLowerCase() !== NATIVE_TOKEN_ADDRESS.toLowerCase();

	return (
		<>
			<div className="bn-relative">
				<InflightBanner
					statusCode={statusCode}
					input={input}
					output={output}
					timeStamp={timestamp}
					protocol={data.info.routingMode === "manual" ? data.info.protocol : undefined}
					refuel={data.info.routingMode === "manual" ? data.info.refuel : null}
				/>

				<div className="bn-flex bn-flex-col bn-justify-center bn-w-full bn-my-4">
					<h2 className="bn-text-center bn-text-xl bn-font-medium bn-leading-6 bn-text-primary bn-mb-1">
						{getTitle(
							statusCode,
							data,
							routingMode === "manual" ? data.info.protocol.name : undefined,
							isGasless,
						)}
					</h2>
					<RotatingText
						texts={getSubtitle(
							statusCode,
							data,
							primaryInput,
							primaryOutput,
							inputChainName,
							outputChainName,
						)}
					/>
				</div>

				<InfoSection
					routeData={data.info}
					openFaq={() => toggleFaq(true)}
					openShare={() => toggleShare(true)}
				/>

				<ModalCloseBtn
					classNames="bn-absolute bn-right-3 bn-top-2 bn-bg-layer-1 bn-rounded-full"
					closeModal={() => {
						if (paramAmount?.[0] && refetch) refetch();
						dispatch(setIsFetchingDisabled(false));
						dispatch(setScreenTab(ScreenTab.HOME));
					}}
				/>

				{/* {isCompleted && <Confetti />} */}
				{/* <RewardsBar rebateDetails={rebateDetails} /> */}
				<Rewards classNames="bn-rounded-md bn-mt-1.5">
					{currentDuneLink && (
						<a
							href={currentDuneLink}
							target="_blank"
							rel="noreferrer"
							className="bn-text-primary bn-underline bn-text-sm bn-font-semibold"
						>
							View Dashboard
						</a>
					)}
				</Rewards>
			</div>

			{isExpired && (
				<Button
					label="Retry with suggested slippage"
					classNames="bn-mt-2"
					onClick={retry}
				/>
			)}

			<FAQ isVisible={isFaqOpen} closePanel={() => toggleFaq(!isFaqOpen)} />
			<Share
				isVisible={isShareOpen}
				closePanel={() => toggleShare(!isShareOpen)}
				txHash={requestHash}
			/>
		</>
	);
};
