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

import type { RefuelEndpoint } from "@hooks/apis/common/quote/types";
import type { ReduxStateType } from "@store/types";
import { adjustDecimals } from "@utils/adjustDecimals";
import { RefuelChip } from "./RefuelChip";

export const Amount = ({
	amount,
	setAmount,
	refuel,
}: {
	amount: string;
	setAmount: (value: string) => void;
	refuel?: RefuelEndpoint;
}) => {
	const [isFocused, setIsFocused] = useState(false);
	const inputRef = useRef<HTMLInputElement>(null);
	const locale = useSelector((state: ReduxStateType) => state.settings.language);

	const onUserInput = (value: string) => {
		if (value.match("^[0-9]*[.,]?[0-9]*$")) {
			// Using dot as decimal separator irrespective of the locale used
			// Bungee relies on . for decimal operations
			setAmount(value.replace(/,/g, "."));
		}
	};

	useEffect(() => {
		if (isFocused && inputRef.current) {
			inputRef.current.focus();
		}
	}, [isFocused]);

	return (
		<div
			className="bn-w-full"
			onFocus={() => setIsFocused(true)}
			onBlur={() => setIsFocused(false)}
			// biome-ignore lint/a11y/noNoninteractiveTabindex: <explanation>
			tabIndex={0}
		>
			{isFocused || !amount ? (
				<input
					ref={inputRef}
					type="text"
					onChange={(e) => onUserInput(e.currentTarget.value)}
					value={amount}
					className="bn-text-primary bn-border-none bn-bg-transparent bn-outline-none bn-text-[22px] bn-font-medium bn-aeonik-font bn-w-full bn-text-ellipsis"
					placeholder="0.00"
					inputMode="decimal"
					disabled={!setAmount}
					spellCheck={false}
					onWheel={(e) => (document.activeElement as HTMLElement).blur()}
					id="bn-amount"
					pattern="^[0-9]*[.,]?[0-9]*$"
					autoComplete="off"
				/>
			) : (
				<div className="bn-flex bn-items-center bn-space-x-2">
					<div className="bn-text-primary bn-outline-none bn-text-[22px] bn-font-medium bn-aeonik-font bn-w-fit">
						{adjustDecimals(amount, 6, locale) || "0.00"}
					</div>
					{refuel && <RefuelChip refuel={refuel} />}
				</div>
			)}
		</div>
	);
};
