import { twMerge } from "@utils/tailwindMerge";
import { useEffect, useMemo, useRef, useState } from "react";

export const TokenIcon = ({
	url,
	classNames,
}: {
	url: string;
	classNames?: string;
}) => {
	const FALLBACK_ICON = "https://media.socket.tech/placeholder-new.svg";

	// Normalize and compute base src value from prop
	const baseSrc = useMemo(() => {
		const normalized = url && url.trim() !== "" ? url : undefined;
		return normalized || FALLBACK_ICON;
	}, [url]);

	const [hasError, setHasError] = useState(false);
	const prevUrlRef = useRef(url);

	// Reset error when URL changes
	useEffect(() => {
		if (prevUrlRef.current !== url) {
			setHasError(false);
			prevUrlRef.current = url;
		}
	}, [url]);

	const classes = twMerge(
		"bn-h-6 bn-w-6 bn-rounded-full bn-overflow-hidden bn-relative",
		classNames,
	);

	// Use fallback if image failed to load at runtime, otherwise use computed base src
	const src = hasError ? FALLBACK_ICON : baseSrc;

	return (
		<div className={classes}>
			<img
				src={src}
				width="100%"
				height="100%"
				alt="placeholder icon"
				className="bn-object-cover bn-absolute bn-top-0 bn-left-0"
				onError={() => setHasError(true)}
			/>
			<div className="bn-absolute bn-top-0 bn-left-0 bn-w-full bn-h-full bn-border bn-border-solid bn-border-black/10 bn-rounded-full" />
		</div>
	);
};
