import {
	type Input,
	type Output,
	RequestStatusEnum,
	type STATUS_CODE,
} from "@/types/index";
import type { OrderData } from "@hooks/apis/auto/useAutoHistory";
import { getOrderStatus } from "@utils/getOrderStatus";
import type { InflightInfo } from "./data";

export function getSubtitle(
	_statusId: STATUS_CODE,
	data: InflightInfo,
	input: Input,
	output: Output,
	inputChainName: string,
	outputChainName: string,
) {
	const {
		isCompleted,
		inProgress,
		isExpired,
		isReverted,
		isRefunded,
		isRefunding,
	} = getOrderStatus(_statusId);

	if (inProgress)
		return data.subTitle.inProgress(
			{ chainName: inputChainName, tokenSymbol: input.token.symbol },
			{ chainName: outputChainName, tokenSymbol: output.token.symbol },
		);
	if (isCompleted) return data.subTitle.isCompleted(outputChainName);
	if (isExpired) return data.subTitle.isExpired;
	if (isReverted) return data.subTitle.isReverted;
	if (isRefunded) return data.subTitle.isRefunded;
	if (isRefunding) return data.subTitle.isRefunding;
	return data.subTitle.isPending;
}

export function getTitle(
	statusCode: STATUS_CODE,
	data: InflightInfo,
	protocolName?: string,
	gasless?: boolean,
) {
	const {
		isPending,
		isCompleted,
		inProgress,
		isExpired,
		isReverted,
		isRefunded,
		isRefunding,
	} = getOrderStatus(statusCode);

	if (isExpired) return data.title.isExpired;
	if (isPending) return data.title.isPending;
	if (inProgress) return data.title.inProgress(protocolName, gasless);
	if (isCompleted) return data.title.isCompleted(protocolName);
	if (isReverted) return data.title.isReverted;
	if (isRefunded) return data.title.isRefunded;
	if (isRefunding) return data.title.isRefunding;
}

export function normalizeRouteData(routeData: OrderData) {
	let status: keyof typeof RequestStatusEnum | undefined = routeData?.status;
	let statusCode: STATUS_CODE | undefined = routeData?.statusCode;
	if (routeData?.statusCode === RequestStatusEnum.REFUND_PENDING) {
		if (routeData?.status === "REFUNDED") {
			status = "REFUNDED";
			statusCode = RequestStatusEnum.REFUNDED;
		}

		if (routeData?.status === "REFUND_PENDING") {
			status = "REFUND_PENDING";
			statusCode = RequestStatusEnum.REFUND_PENDING;
		}

		if (routeData?.status === "REVERTED") {
			status = "REVERTED";
			statusCode = RequestStatusEnum.REVERTED;
		}
	}

	return {
		...routeData,
		status,
		statusCode,
	};
}
