import { useMemo, useState } from "react";
import { useCategories } from "../hooks/useCategories";
import { useFormatters } from "../hooks/useFormatters";
import { useItems } from "../hooks/useItems";
import { useTotals } from "../hooks/useTotals";
import { LucideIcon } from "../lib/iconData";
import { useUIStore } from "../stores/uiStore";
import { CategoryFilterDropdown } from "./CategoryFilterDropdown";
import { CategoryHeader } from "./CategoryHeader";
import { ItemCard } from "./ItemCard";

export function CollectionView() {
	const { data: items, isLoading: itemsLoading } = useItems();
	const { data: totals } = useTotals();
	const { data: categories } = useCategories();
	const { weight, price } = useFormatters();
	const openAddPanel = useUIStore((s) => s.openAddPanel);

	const [searchText, setSearchText] = useState("");
	const [categoryFilter, setCategoryFilter] = useState<number | null>(null);

	const filteredItems = useMemo(() => {
		if (!items) return [];
		return items.filter((item) => {
			const matchesSearch =
				searchText === "" ||
				item.name.toLowerCase().includes(searchText.toLowerCase());
			const matchesCategory =
				categoryFilter === null || item.categoryId === categoryFilter;
			return matchesSearch && matchesCategory;
		});
	}, [items, searchText, categoryFilter]);

	const hasActiveFilters = searchText !== "" || categoryFilter !== null;

	if (itemsLoading) {
		return (
			<div className="animate-pulse space-y-6">
				<div className="h-6 bg-gray-200 rounded w-48" />
				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
					{[1, 2, 3].map((i) => (
						<div key={i} className="h-40 bg-gray-200 rounded-xl" />
					))}
				</div>
			</div>
		);
	}

	if (!items || items.length === 0) {
		return (
			<div className="py-16 text-center">
				<div className="max-w-md mx-auto">
					<div className="mb-4">
						<LucideIcon
							name="backpack"
							size={48}
							className="text-gray-400 mx-auto"
						/>
					</div>
					<h2 className="text-xl font-semibold text-gray-900 mb-2">
						Your collection is empty
					</h2>
					<p className="text-sm text-gray-500 mb-6">
						Start cataloging your gear by adding your first item. Track weight,
						price, and organize by category.
					</p>
					<button
						type="button"
						onClick={openAddPanel}
						className="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-700 hover:bg-gray-800 text-white text-sm font-medium rounded-lg transition-colors"
					>
						<svg
							aria-hidden="true"
							className="w-4 h-4"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								strokeLinecap="round"
								strokeLinejoin="round"
								strokeWidth={2}
								d="M12 4v16m8-8H4"
							/>
						</svg>
						Add your first item
					</button>
				</div>
			</div>
		);
	}

	// Build category totals lookup
	const categoryTotalsMap = new Map<
		number,
		{ totalWeight: number; totalCost: number; itemCount: number }
	>();
	if (totals?.categories) {
		for (const ct of totals.categories) {
			categoryTotalsMap.set(ct.categoryId, {
				totalWeight: ct.totalWeight,
				totalCost: ct.totalCost,
				itemCount: ct.itemCount,
			});
		}
	}

	// Group filtered items by categoryId (used when no active filters)
	const groupedItems = new Map<
		number,
		{
			items: typeof filteredItems;
			categoryName: string;
			categoryIcon: string;
		}
	>();

	for (const item of filteredItems) {
		const group = groupedItems.get(item.categoryId);
		if (group) {
			group.items.push(item);
		} else {
			groupedItems.set(item.categoryId, {
				items: [item],
				categoryName: item.categoryName,
				categoryIcon: item.categoryIcon,
			});
		}
	}

	return (
		<>
			{/* Collection stats card */}
			{totals?.global && (
				<div className="bg-white rounded-xl border border-gray-100 p-5 mb-6">
					<div className="flex items-center gap-8">
						<div className="flex flex-col items-center gap-1">
							<LucideIcon name="layers" size={14} className="text-gray-400" />
							<span className="text-xs text-gray-500">Items</span>
							<span className="text-sm font-semibold text-gray-900">
								{totals.global.itemCount}
							</span>
						</div>
						<div className="flex flex-col items-center gap-1">
							<LucideIcon name="weight" size={14} className="text-gray-400" />
							<span className="text-xs text-gray-500">Total Weight</span>
							<span className="text-sm font-semibold text-gray-900">
								{weight(totals.global.totalWeight)}
							</span>
						</div>
						<div className="flex flex-col items-center gap-1">
							<LucideIcon
								name="credit-card"
								size={14}
								className="text-gray-400"
							/>
							<span className="text-xs text-gray-500">Total Spent</span>
							<span className="text-sm font-semibold text-gray-900">
								{price(totals.global.totalCost)}
							</span>
						</div>
					</div>
				</div>
			)}

			{/* Search/filter toolbar */}
			<div className="sticky top-0 z-10 bg-gray-50/95 backdrop-blur-sm border-b border-gray-100 -mx-4 px-4 py-3 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 mb-6">
				<div className="flex gap-3 items-center">
					<div className="relative flex-1">
						<input
							type="text"
							placeholder="Search items..."
							value={searchText}
							onChange={(e) => setSearchText(e.target.value)}
							className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
						/>
						{searchText && (
							<button
								type="button"
								onClick={() => setSearchText("")}
								className="absolute right-2 top-1/2 -translate-y-1/2 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>
					<CategoryFilterDropdown
						value={categoryFilter}
						onChange={setCategoryFilter}
						categories={categories ?? []}
					/>
				</div>
				{hasActiveFilters && (
					<p className="text-xs text-gray-500 mt-2">
						Showing {filteredItems.length} of {items.length} items
					</p>
				)}
			</div>

			{/* Filtered results */}
			{hasActiveFilters ? (
				filteredItems.length === 0 ? (
					<div className="py-12 text-center">
						<p className="text-sm text-gray-500">No items match your search</p>
					</div>
				) : (
					<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
						{filteredItems.map((item) => (
							<ItemCard
								key={item.id}
								id={item.id}
								name={item.name}
								weightGrams={item.weightGrams}
								priceCents={item.priceCents}
								quantity={item.quantity}
								categoryName={item.categoryName}
								categoryIcon={item.categoryIcon}
								imageFilename={item.imageFilename}
								productUrl={item.productUrl}
							/>
						))}
					</div>
				)
			) : (
				Array.from(groupedItems.entries()).map(
					([
						categoryId,
						{ items: categoryItems, categoryName, categoryIcon },
					]) => {
						const catTotals = categoryTotalsMap.get(categoryId);
						return (
							<div key={categoryId} className="mb-8">
								<CategoryHeader
									categoryId={categoryId}
									name={categoryName}
									icon={categoryIcon}
									totalWeight={catTotals?.totalWeight ?? 0}
									totalCost={catTotals?.totalCost ?? 0}
									itemCount={catTotals?.itemCount ?? categoryItems.length}
								/>
								<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
									{categoryItems.map((item) => (
										<ItemCard
											key={item.id}
											id={item.id}
											name={item.name}
											weightGrams={item.weightGrams}
											priceCents={item.priceCents}
											quantity={item.quantity}
											categoryName={categoryName}
											categoryIcon={categoryIcon}
											imageFilename={item.imageFilename}
											productUrl={item.productUrl}
										/>
									))}
								</div>
							</div>
						);
					},
				)
			)}
		</>
	);
}
