import { useDebounce } from "@uidotdev/usehooks";
import type React from "react";
import { useEffect, useState } from "react";
import { useTheme } from "../../hooks/useTheme";
import { getBorderRadius } from "../../utils/getBorderRadius";
import { MIcon } from "../common/MIcon";

export const SearchBar = ({
	setValue,
}: {
	setValue: React.Dispatch<React.SetStateAction<string>>;
}) => {
	const theme = useTheme();
	const [input, setInput] = useState<string>("");

	const deboundedInput = useDebounce(input, 400);

	useEffect(() => {
		setValue(deboundedInput);
	}, [deboundedInput, setValue]);

	return (
		<div
			className="bn-w-full bn-flex-1 bn-bg-layer-2 bn-pl-2 bn-pr-10 bn-flex bn-items-center bn-h-10 bn-relative"
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
		>
			{/* placeholder */}
			{!input && (
				<div className="bn-text-secondary bn-text-[13px] bn-absolute bn-left-10">
					Example: USDC Optimism
				</div>
			)}

			<MIcon name="search" classNames="bn-text-primary" />
			<input
				className="bn-relative bn-ml-2 bn-text-primary bn-text-base bn-px-0 bn-w-full bn-border-none bn-bg-transparent bn-overflow-ellipsis"
				type="text"
				value={input}
				onChange={(e) => setInput(e.target.value)}
				spellCheck={false}
				id="bn-token-search"
				autoComplete="off"
			/>

			{/* clear button */}
			{input && (
				<button
					type="button"
					onClick={() => {
						setInput("");
						setValue("");
					}}
					className="bn-text-primary bn-absolute bn-right-2 bn-w-6 bn-h-6 bn-border-0 bn-p-0 bn-bg-transparent bn-cursor-pointer"
				>
					<MIcon name="backspace" />
				</button>
			)}
		</div>
	);
};
