import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useTransactionReceipt } from "wagmi";

import type { Output } from "@/types/index";
import type { ManualOrderData } from "@hooks/apis/auto/useAutoHistory";
import { useManualStatus } from "@hooks/apis/manual/useManualStatus";
import { updateManualHistory } from "@store/globalSlice";
import { type InflightInfo, ManualData } from "../common/data";
import { InFlightLayout } from "../layout";

export const ManualInFlight = ({
	initialData,
}: { initialData: ManualOrderData }) => {
	const dispatch = useDispatch();

	const {
		data: txResolved,
		error: txError,
		isLoading: isTxReceiptLoading,
	} = useTransactionReceipt({
		// biome-ignore format:
		hash: initialData?.requestHash as `0x${string}`,
		query: {
			retry: 5,
			retryDelay: 3000,
		},
	});

	const { data: statusData, isLoading: isStatusLoading } = useManualStatus({
		requestHash: initialData.requestHash,
		fromChainId: initialData.primaryInput.token.chainId,
	});

	const [routeData, setRouteData] = useState<ManualOrderData>();
	/**
	 * Setting StatusCode to 2 when source tx confirmed or when status is returned as pending
	 * Setting StatusCode to 3 when dest tx is confirmed
	 *
	 * In case of swaps, marking as complete after the tx is confirmed on source
	 */
	const resolveManualOrderStatus = (): ManualOrderData => {
		const isTxComplete = initialData.statusCode >= 3 && initialData.statusCode < 5;

		if (isTxComplete) return initialData;

		const hasFailed = txResolved && txResolved.status === "reverted";

		if (hasFailed) {
			return {
				...initialData,
				status: "REVERTED",
				statusCode: 9,
			};
		}

		if (initialData.isSwapRoute && txResolved?.status === "success") {
			return {
				...initialData,
				status: "FULFILLED",
				statusCode: 3,
			};
		}

		if (statusData?.destinationTxStatus === "COMPLETED") {
			const _output: Output = {
				...initialData.primaryOutput,
				fulfilledAmount: statusData.toAmount,
			};

			return {
				...initialData,
				status: "FULFILLED",
				statusCode: 3,
				output: [_output],
				primaryOutput: _output,
			};
		}

		if (
			(statusData?.destinationTxStatus === "PENDING" ||
				txResolved?.status === "success") &&
			!txError
		) {
			return {
				...initialData,
				status: "EXTRACTED",
				statusCode: 2,
				srcTimestamp: routeData?.srcTimestamp || Math.floor(Date.now() / 1000),
			};
		}

		return initialData;
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		const nextData = resolveManualOrderStatus();
		setRouteData(nextData);
	}, [
		initialData,
		txResolved,
		txError,
		statusData,
		isStatusLoading,
		isTxReceiptLoading,
	]);

	// Update localStorage manualHistory after routeData is set
	useEffect(() => {
		if (routeData) {
			dispatch(
				updateManualHistory({
					address: routeData.sender.toLowerCase(),
					data: routeData,
				}),
			);
		}
	}, [routeData, dispatch]);

	const data: InflightInfo = {
		title: ManualData.title,
		subTitle: ManualData.subTitle,
		info: routeData ?? initialData,
	};

	return <InFlightLayout data={data} />;
};
