import { Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import {
	useGlobalItem,
	useGlobalItems,
	useLinkItem,
	useUnlinkItem,
} from "../hooks/useGlobalItems";
import { GearImage } from "./GearImage";

interface LinkToGlobalItemProps {
	itemId: number;
	linkedGlobalItemId?: number | null;
}

export function LinkToGlobalItem({
	itemId,
	linkedGlobalItemId,
}: LinkToGlobalItemProps) {
	const [isOpen, setIsOpen] = useState(false);
	const [searchInput, setSearchInput] = useState("");
	const [debouncedQuery, setDebouncedQuery] = useState("");

	const linkItem = useLinkItem();
	const unlinkItem = useUnlinkItem();
	const { data: linkedItem } = useGlobalItem(linkedGlobalItemId ?? null);
	const { data: searchResults, isLoading: isSearching } = useGlobalItems(
		isOpen && debouncedQuery ? debouncedQuery : undefined,
	);

	useEffect(() => {
		const timer = setTimeout(() => {
			setDebouncedQuery(searchInput);
		}, 300);
		return () => clearTimeout(timer);
	}, [searchInput]);

	function handleLink(globalItemId: number) {
		linkItem.mutate(
			{ itemId, globalItemId },
			{
				onSuccess: () => {
					setIsOpen(false);
					setSearchInput("");
					setDebouncedQuery("");
				},
			},
		);
	}

	function handleUnlink() {
		unlinkItem.mutate(itemId);
	}

	// Already linked state
	if (linkedGlobalItemId && linkedItem) {
		return (
			<div className="rounded-lg border border-gray-100 bg-gray-50 p-3">
				<div className="flex items-center justify-between gap-3">
					<div className="flex items-center gap-2 min-w-0">
						<svg
							className="w-4 h-4 text-green-500 shrink-0"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								strokeLinecap="round"
								strokeLinejoin="round"
								strokeWidth={2}
								d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
							/>
						</svg>
						<Link
							to="/global-items/$globalItemId"
							params={{ globalItemId: String(linkedGlobalItemId) }}
							className="text-sm text-gray-700 hover:text-gray-900 truncate"
						>
							{linkedItem.brand} {linkedItem.model}
						</Link>
					</div>
					<button
						type="button"
						onClick={handleUnlink}
						disabled={unlinkItem.isPending}
						className="text-xs text-gray-400 hover:text-red-500 transition-colors shrink-0"
					>
						{unlinkItem.isPending ? "..." : "Unlink"}
					</button>
				</div>
			</div>
		);
	}

	// Collapsed / trigger state
	if (!isOpen) {
		return (
			<button
				type="button"
				onClick={() => setIsOpen(true)}
				className="w-full flex items-center gap-2 px-3 py-2.5 rounded-lg border border-dashed border-gray-200 text-sm text-gray-400 hover:text-gray-600 hover:border-gray-300 transition-colors"
			>
				<svg
					className="w-4 h-4"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						strokeLinecap="round"
						strokeLinejoin="round"
						strokeWidth={2}
						d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
					/>
				</svg>
				Link to catalog
			</button>
		);
	}

	// Open search state
	return (
		<div className="rounded-lg border border-gray-200 bg-white overflow-hidden">
			<div className="p-3">
				<div className="flex items-center justify-between mb-2">
					<span className="text-xs font-medium text-gray-500">
						Link to global catalog
					</span>
					<button
						type="button"
						onClick={() => {
							setIsOpen(false);
							setSearchInput("");
							setDebouncedQuery("");
						}}
						className="text-gray-400 hover:text-gray-600"
					>
						<svg
							className="w-4 h-4"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								strokeLinecap="round"
								strokeLinejoin="round"
								strokeWidth={2}
								d="M6 18L18 6M6 6l12 12"
							/>
						</svg>
					</button>
				</div>
				<input
					type="text"
					value={searchInput}
					onChange={(e) => setSearchInput(e.target.value)}
					placeholder="Search by brand or model..."
					className="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-200 focus:border-gray-300"
					autoFocus
				/>
			</div>

			{/* Search results */}
			{debouncedQuery && (
				<div className="border-t border-gray-100 max-h-48 overflow-y-auto">
					{isSearching ? (
						<div className="p-3 text-center">
							<span className="text-xs text-gray-400">Searching...</span>
						</div>
					) : searchResults && searchResults.length > 0 ? (
						<div>
							{searchResults.map((item) => (
								<button
									key={item.id}
									type="button"
									onClick={() => handleLink(item.id)}
									disabled={linkItem.isPending}
									className="w-full text-left px-3 py-2 hover:bg-gray-50 transition-colors flex items-center gap-2"
								>
									{item.imageUrl ? (
										<div className="w-8 h-8 rounded overflow-hidden shrink-0">
											<GearImage src={item.imageUrl} alt="" cover />
										</div>
									) : (
										<div className="w-8 h-8 rounded bg-gray-100 shrink-0" />
									)}
									<div className="min-w-0">
										<p className="text-xs text-gray-400">{item.brand}</p>
										<p className="text-sm text-gray-900 truncate">
											{item.model}
										</p>
									</div>
								</button>
							))}
						</div>
					) : (
						<div className="p-3 text-center">
							<span className="text-xs text-gray-400">No items found</span>
						</div>
					)}
				</div>
			)}
		</div>
	);
}
