import { useEffect, useState } from "react";
import type React from "react";

import { SearchIcon } from "@components/common/Icons";
import { useIsMobile } from "@hooks/useIsMobile";
import { useDebounce } from "@uidotdev/usehooks";
import { twMerge } from "tailwind-merge";
import { useTheme } from "../../hooks/useTheme";
import { getBorderRadius } from "../../utils/getBorderRadius";
import { MIcon } from "../common/MIcon";

import Lottie from "react-lottie";

import searchBarAnimationData from "@assets/lottie/search-bar.json";

const searchBarOptions = {
	loop: true,
	autoplay: true,
	animationData: searchBarAnimationData,
	renderSettings: {
		preserveAspectRatio: "xMidyMid slice",
	},
};

export const SearchBar = ({
	setValue,
}: {
	setValue: React.Dispatch<React.SetStateAction<string>>;
}) => {
	const theme = useTheme();
	const isMobile = useIsMobile();
	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 bn-overflow-hidden"
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
		>
			<SearchIcon
				className={twMerge(
					"bn-size-5",
					input ? "*:bn-fill-primary" : "*:bn-fill-secondary",
				)}
			/>

			{!input && (
				<div className="bn-absolute -bn-translate-y-[48%] bn-top-1/2 bn-left-2 bn-h-20 bn-w-[400px] !bn-scale-100">
					<Lottie options={searchBarOptions} width={400} height={80} />
				</div>
			)}

			<input
				ref={(el) => {
					if (el && !isMobile) el.focus();
				}}
				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 placeholder:bn-text-secondary"
				type="text"
				value={input}
				onChange={(e) => setInput(e.target.value)}
				spellCheck={false}
				id="bn-token-search"
				autoComplete="off"
			/>

			{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>
	);
};
