import type { EndPoint } from "@hooks/apis/useFetchQuote";
import { Trans } from "@lingui/macro";
import { adjustDecimals } from "@utils/adjustDecimals";
import { toFixedSafe } from "@utils/toFixedSafe";
import { useColor } from "@utils/useColor";
import type { Token } from "../../Providers/ConfigProvider";

export const PercentageBar = ({
	ratio,
	endpoints,
	showHeading = false,
}: { ratio: number[]; endpoints: EndPoint[]; showHeading?: boolean }) => {
	const tokens = endpoints.map((endpoint) => endpoint.token);
	return (
		<div className="bn-flex bn-flex-col bn-space-y-3 bn-w-full">
			{showHeading && (
				<p className="bn-text-secondary bn-text-[13px] bn-font-medium">
					<Trans>Estimated token received</Trans>
				</p>
			)}
			<Bar values={ratio} tokens={tokens} />
			<div className="bn-flex bn-items-center bn-justify-between">
				<TokenInfo endpoint={endpoints[0]} percent={toFixedSafe(ratio[0] * 100)} />
				<TokenInfo endpoint={endpoints[1]} percent={toFixedSafe(ratio[1] * 100)} />
			</div>
		</div>
	);
};

const Bar = ({ values, tokens }: { values: number[]; tokens: Token[] }) => {
	// Note: not optimized for more than 2 tokens
	const color1 = useColor(tokens[0]?.logoURI);
	const color2 = useColor(tokens[1]?.logoURI);
	const colors = [color1, color2];

	return (
		<div className="bn-w-full bn-h-2.5 bn-rounded-full bn-overflow-hidden bn-flex bn-justify-end">
			{values.map((value, index) => {
				const _percentage = toFixedSafe(value * 100);

				// biome-ignore format:
				const _width = `${_percentage}%`;

				// biome-ignore format:
				const _key = `${_width}-${index}`

				return (
					<div
						className="bn-h-full"
						style={{ width: _width, background: colors[index] }}
						key={_key}
					/>
				);
			})}
		</div>
	);
};

const TokenInfo = ({
	endpoint,
	percent,
}: { endpoint: EndPoint; percent: number }) => {
	const color = useColor(endpoint.token.logoURI);
	return (
		<div className="bn-flex bn-items-center bn-space-x-1.5 bn-font-medium bn-aeonik-font bn-text-[13px]">
			<div className="bn-size-1.5 bn-rounded-full" style={{ background: color }} />
			<p className="bn-text-primary">
				{!!endpoint.valueInUsd && (
					<span>${adjustDecimals(endpoint.valueInUsd)} of </span>
				)}
				{endpoint.token.symbol}
			</p>
			<p className="bn-text-secondary">({percent}%)</p>
		</div>
	);
};
