import { useNavigate } from "@tanstack/react-router";
import { useFormatters } from "../hooks/useFormatters";
import { useDuplicateItem } from "../hooks/useItems";
import { LucideIcon } from "../lib/iconData";
import { useUIStore } from "../stores/uiStore";
import { ClassificationBadge } from "./ClassificationBadge";
import { GearImage, imageContainerBg } from "./GearImage";

interface ItemCardProps {
	id: number;
	name: string;
	weightGrams: number | null;
	priceCents: number | null;
	quantity?: number;
	categoryName: string;
	categoryIcon: string;
	imageFilename: string | null;
	imageUrl?: string | null;
	productUrl?: string | null;
	brand?: string | null;
	dominantColor?: string | null;
	cropZoom?: number | null;
	cropX?: number | null;
	cropY?: number | null;
	onRemove?: () => void;
	classification?: string;
	onClassificationCycle?: () => void;
}

export function ItemCard({
	id,
	name,
	weightGrams,
	priceCents,
	quantity,
	categoryName,
	categoryIcon,
	imageFilename: _imageFilename,
	imageUrl,
	productUrl,
	brand,
	dominantColor,
	cropZoom,
	cropX,
	cropY,
	onRemove,
	classification,
	onClassificationCycle,
}: ItemCardProps) {
	const { weight, price } = useFormatters();
	const navigate = useNavigate();
	const openExternalLink = useUIStore((s) => s.openExternalLink);
	const duplicateItem = useDuplicateItem();

	return (
		<button
			type="button"
			onClick={() =>
				navigate({ to: "/items/$itemId", params: { itemId: String(id) } })
			}
			className="relative w-full text-left bg-white rounded-xl border border-gray-100 hover:border-gray-200 hover:shadow-sm transition-all overflow-hidden group"
		>
			{!onRemove && (
				<span
					role="button"
					tabIndex={0}
					onClick={(e) => {
						e.stopPropagation();
						duplicateItem.mutate(id, {
							onSuccess: (newItem) => {
								navigate({
									to: "/items/$itemId",
									params: { itemId: String(newItem.id) },
								});
							},
						});
					}}
					onKeyDown={(e) => {
						if (e.key === "Enter" || e.key === " ") {
							e.stopPropagation();
							duplicateItem.mutate(id, {
								onSuccess: (newItem) => {
									navigate({
										to: "/items/$itemId",
										params: { itemId: String(newItem.id) },
									});
								},
							});
						}
					}}
					className={`absolute top-2 ${productUrl ? "right-10" : "right-2"} z-10 w-6 h-6 flex items-center justify-center rounded-full bg-gray-100/80 text-gray-400 hover:bg-blue-100 hover:text-blue-500 opacity-0 group-hover:opacity-100 transition-all cursor-pointer`}
					title="Duplicate item"
				>
					<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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
						/>
					</svg>
				</span>
			)}
			{productUrl && (
				<span
					role="button"
					tabIndex={0}
					onClick={(e) => {
						e.stopPropagation();
						openExternalLink(productUrl);
					}}
					onKeyDown={(e) => {
						if (e.key === "Enter" || e.key === " ") {
							e.stopPropagation();
							openExternalLink(productUrl);
						}
					}}
					className={`absolute top-2 ${onRemove ? "right-10" : "right-2"} z-10 w-6 h-6 flex items-center justify-center rounded-full bg-gray-100/80 text-gray-400 hover:bg-gray-200 hover:text-gray-600 opacity-0 group-hover:opacity-100 transition-all cursor-pointer`}
					title="Open product link"
				>
					<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="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6M15 3h6v6M10 14L21 3"
						/>
					</svg>
				</span>
			)}
			{onRemove && (
				<span
					role="button"
					tabIndex={0}
					onClick={(e) => {
						e.stopPropagation();
						onRemove();
					}}
					onKeyDown={(e) => {
						if (e.key === "Enter" || e.key === " ") {
							e.stopPropagation();
							onRemove();
						}
					}}
					className="absolute top-2 right-2 z-10 w-6 h-6 flex items-center justify-center rounded-full bg-gray-100/80 text-gray-400 hover:bg-red-100 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all cursor-pointer"
					title="Remove from setup"
				>
					<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>
				</span>
			)}
			<div
				className="aspect-[4/3] overflow-hidden"
				style={{
					backgroundColor: imageUrl
						? imageContainerBg(dominantColor)
						: undefined,
				}}
			>
				{imageUrl ? (
					<GearImage
						src={imageUrl}
						alt={name}
						dominantColor={dominantColor}
						cropZoom={cropZoom}
						cropX={cropX}
						cropY={cropY}
					/>
				) : (
					<div className="w-full h-full bg-gray-50 flex flex-col items-center justify-center">
						<LucideIcon
							name={categoryIcon}
							size={36}
							className="text-gray-400"
						/>
					</div>
				)}
			</div>
			<div className="p-4">
				{brand && (
					<p className="text-xs font-medium text-gray-400 uppercase tracking-wide mb-0.5">
						{brand}
					</p>
				)}
				<div className="flex items-center gap-1.5 mb-2">
					<h3 className="text-sm font-semibold text-gray-900 truncate min-w-0">
						{brand ? name.replace(`${brand} `, "") : name}
					</h3>
					{quantity != null && quantity > 1 && (
						<span className="shrink-0 inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
							&times;{quantity}
						</span>
					)}
				</div>
				<div className="flex flex-wrap gap-1.5">
					{weightGrams != null && (
						<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-400">
							{weight(weightGrams)}
						</span>
					)}
					{priceCents != null && (
						<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-500">
							{price(priceCents)}
						</span>
					)}
					<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-50 text-gray-600">
						<LucideIcon
							name={categoryIcon}
							size={14}
							className="inline-block mr-1 text-gray-500"
						/>{" "}
						{categoryName}
					</span>
					{classification && onClassificationCycle && (
						<ClassificationBadge
							classification={classification}
							onCycle={onClassificationCycle}
						/>
					)}
				</div>
			</div>
		</button>
	);
}
