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

import { Amount } from "@components/common/Amount";
import { Balance } from "@components/common/Balance";
import { PercentageBar } from "@components/common/PercentageBar";
import { PriceImpact } from "@components/common/PriceImpact";
import { UsdValue } from "@components/common/UsdValue";
import { useActiveRoute } from "@hooks/apis/common/quote/useActiveRoute";
import { useTheme } from "@hooks/useTheme";
import { useTokenBalance } from "@hooks/useTokenBalance";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { formatValue } from "@utils/formatValue";
import { getBorderRadius } from "@utils/getBorderRadius";
import { OutputToken } from "./OutputToken";

export const Output = () => {
	const { data: activeRoute, isLoading } = useActiveRoute();
	const [amount, setAmount] = useState<string>("");
	const locale = useSelector((state: ReduxStateType) => state.settings.language);

	useEffect(() => {
		const _output = activeRoute?.output[0];
		const _token = _output?.token;

		if (_output && _token) {
			const _outputFormatted = formatValue(_output.amount, _token?.decimals);
			setAmount(_outputFormatted);
		} else {
			setAmount("");
		}
	}, [activeRoute]);

	// to get token balance
	const selectedOutputTokens = useSelector(
		(state: ReduxStateType) => state.quoteParams.toTokens,
	);
	const activeToToken = useMemo(
		() => selectedOutputTokens?.[0],
		[selectedOutputTokens],
	);

	const { balance: tokenBalance, isLoading: isFetchingBalance } = useTokenBalance(
		{ token: activeToToken },
	);

	const activeTokenBalanceFormatted = useMemo(() => {
		if (tokenBalance && activeToToken && !isFetchingBalance) {
			return formatValue(tokenBalance, activeToToken.decimals);
		}
		return null;
	}, [tokenBalance, activeToToken, isFetchingBalance]);

	// to get usd value
	const output = activeRoute?.output?.[0];
	const multiTokensAdded = activeRoute?.output?.length
		? activeRoute.output.length > 1
		: false;

	// Note: temporary
	const ratio = useSelector(
		(state: ReduxStateType) => state.quoteParams.outputRatio,
	);

	// amount with loader
	const renderAmount = () => {
		if (isLoading) return <Loader />;
		if (!multiTokensAdded) {
			return (
				<Amount
					amount={amount}
					setAmount={() => {}}
					refuel={activeRoute?.refuel?.output}
				/>
			);
		}
		return null;
	};

	// usd value with loader
	const renderUsdValue = () => {
		if (isLoading) {
			return (
				<span className="bn-text-sm bn-text-secondary bn-font-medium bn-leading-[16.8px]">
					Fetching the best guaranteed price...
				</span>
			);
		}

		if (output?.valueInUsd) {
			return <UsdValue value={adjustDecimals(output.valueInUsd, 2, locale)} />;
		}

		return null;
	};

	function renderBalance() {
		if (isFetchingBalance) {
			return (
				<div className="bn-h-[22px] bn-w-[100px] bn-animate-pulse bn-bg-layer-3" />
			);
		}

		if (activeToToken)
			return <Balance balance={activeTokenBalanceFormatted || "0.00"} />;
	}

	// percentage bar or usd value & balance
	const renderBar = () => {
		// if (multiTokensAdded)
		// 	return (
		// 		<div className="bn-mt-5">
		// 			<PercentageBar ratio={ratio} endpoints={activeRoute?.output} />
		// 		</div>
		// 	);

		return (
			<div className="bn-flex bn-items-center bn-w-full bn-mt-2.5 bn-h-5 bn-justify-between">
				<div className="bn-flex bn-items-center bn-space-x-1">
					<span>{renderUsdValue()}</span>
					<PriceImpact />
					{/* <RewardDisplay rebateDetails={activeRoute?.rebateDetails} /> */}
				</div>
				{renderBalance()}
			</div>
		);
	};

	return (
		<div className="bn-px-[18px] bn-pt-[35px] bn-pb-[19px]">
			{/* Amount and Token */}
			<div className="bn-flex bn-items-center bn-justify-between">
				{renderAmount()}
				{multiTokensAdded && isLoading ? null : <OutputToken />}
			</div>

			{/* USD value and Balance with Percentage Bar*/}
			{renderBar()}
		</div>
	);
};

const Loader = () => {
	const theme = useTheme();
	return (
		<div
			className="bn-h-[19px] bn-bg-layer-3 bn-min-w-[140px] bn-animate-pulse"
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 6) }}
		/>
	);
};

// const RewardDisplay = ({
// 	rebateDetails,
// }: { rebateDetails?: RebateDetails }) => {
// 	const locale = useSelector((state: ReduxStateType) => state.settings.language);
// 	if (!rebateDetails || rebateDetails?.amount === "0") return null;

// 	const token = rebateDetails.token;
// 	const amount = rebateDetails.amount;
// 	const formattedAmount = formatValue(amount, token.decimals);

// 	return (
// 		<div className="bn-text-accent-3 bn-text-sm bn-aeonik-font">
// 			(+{adjustDecimals(formattedAmount, 3, locale)} {token.symbol})
// 		</div>
// 	);
// };
