import { useEffect, useRef, useState } from "react";
import { LucideIcon } from "../lib/iconData";

interface CategoryFilterDropdownProps {
	value: number | null;
	onChange: (value: number | null) => void;
	categories: Array<{ id: number; name: string; icon: string }>;
}

export function CategoryFilterDropdown({
	value,
	onChange,
	categories,
}: CategoryFilterDropdownProps) {
	const [isOpen, setIsOpen] = useState(false);
	const [searchText, setSearchText] = useState("");
	const containerRef = useRef<HTMLDivElement>(null);
	const searchInputRef = useRef<HTMLInputElement>(null);

	const selectedCategory = categories.find((c) => c.id === value);

	const filteredCategories = categories.filter((c) =>
		c.name.toLowerCase().includes(searchText.toLowerCase()),
	);

	// Click-outside dismiss
	useEffect(() => {
		function handleClickOutside(e: MouseEvent) {
			if (
				containerRef.current &&
				!containerRef.current.contains(e.target as Node)
			) {
				setIsOpen(false);
				setSearchText("");
			}
		}
		document.addEventListener("mousedown", handleClickOutside);
		return () => document.removeEventListener("mousedown", handleClickOutside);
	}, []);

	// Escape key dismiss
	useEffect(() => {
		function handleKeyDown(e: KeyboardEvent) {
			if (e.key === "Escape" && isOpen) {
				setIsOpen(false);
				setSearchText("");
			}
		}
		document.addEventListener("keydown", handleKeyDown);
		return () => document.removeEventListener("keydown", handleKeyDown);
	}, [isOpen]);

	// Auto-focus search input when dropdown opens
	useEffect(() => {
		if (isOpen && searchInputRef.current) {
			searchInputRef.current.focus();
		}
	}, [isOpen]);

	function handleSelect(categoryId: number | null) {
		onChange(categoryId);
		setIsOpen(false);
		setSearchText("");
	}

	return (
		<div ref={containerRef} className="relative">
			{/* Trigger button */}
			<button
				type="button"
				onClick={() => setIsOpen((prev) => !prev)}
				className="flex items-center gap-2 px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white hover:bg-gray-50 transition-colors whitespace-nowrap"
			>
				{selectedCategory ? (
					<>
						<LucideIcon
							name={selectedCategory.icon}
							size={14}
							className="text-gray-500 shrink-0"
						/>
						<span className="text-gray-900">{selectedCategory.name}</span>
					</>
				) : (
					<span className="text-gray-600">All categories</span>
				)}
				{selectedCategory ? (
					<button
						type="button"
						onClick={(e) => {
							e.stopPropagation();
							onChange(null);
						}}
						className="ml-1 text-gray-400 hover:text-gray-600"
					>
						<svg
							className="w-3.5 h-3.5"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								strokeLinecap="round"
								strokeLinejoin="round"
								strokeWidth={2}
								d="M6 18L18 6M6 6l12 12"
							/>
						</svg>
					</button>
				) : (
					<svg
						className="w-4 h-4 text-gray-400"
						fill="none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							strokeLinecap="round"
							strokeLinejoin="round"
							strokeWidth={2}
							d="M19 9l-7 7-7-7"
						/>
					</svg>
				)}
			</button>

			{/* Dropdown panel */}
			{isOpen && (
				<div className="absolute right-0 z-20 mt-1 min-w-[220px] bg-white border border-gray-200 rounded-lg shadow-lg">
					{/* Search input */}
					<div className="p-2 border-b border-gray-100">
						<input
							ref={searchInputRef}
							type="text"
							placeholder="Search categories..."
							value={searchText}
							onChange={(e) => setSearchText(e.target.value)}
							className="w-full px-2.5 py-1.5 border border-gray-200 rounded text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
						/>
					</div>

					{/* Option list */}
					<ul className="max-h-60 overflow-y-auto py-1">
						{/* All categories option */}
						{(searchText === "" ||
							"all categories".includes(searchText.toLowerCase())) && (
							<li>
								<button
									type="button"
									onClick={() => handleSelect(null)}
									className={`w-full text-left px-3 py-2 text-sm cursor-pointer hover:bg-gray-50 ${
										value === null
											? "bg-gray-50 font-medium text-gray-900"
											: "text-gray-700"
									}`}
								>
									All categories
								</button>
							</li>
						)}

						{/* Category options */}
						{filteredCategories.map((cat) => (
							<li key={cat.id}>
								<button
									type="button"
									onClick={() => handleSelect(cat.id)}
									className={`w-full text-left px-3 py-2 text-sm cursor-pointer flex items-center gap-2 hover:bg-gray-50 ${
										cat.id === value
											? "bg-gray-50 font-medium text-gray-900"
											: "text-gray-700"
									}`}
								>
									<LucideIcon
										name={cat.icon}
										size={16}
										className="text-gray-500 shrink-0"
									/>
									{cat.name}
								</button>
							</li>
						))}

						{/* No results */}
						{filteredCategories.length === 0 &&
							!(
								searchText === "" ||
								"all categories".includes(searchText.toLowerCase())
							) && (
								<li className="px-3 py-2 text-sm text-gray-400">
									No categories found
								</li>
							)}
					</ul>
				</div>
			)}
		</div>
	);
}
