import { createFileRoute } from "@tanstack/react-router";
import { AnimatePresence, motion } from "framer-motion";
import { useMemo, useRef, useState } from "react";
import { z } from "zod";
import { CategoryFilterDropdown } from "../../components/CategoryFilterDropdown";
import { CategoryHeader } from "../../components/CategoryHeader";
import { CreateThreadModal } from "../../components/CreateThreadModal";
import { ItemCard } from "../../components/ItemCard";
import { SetupCard } from "../../components/SetupCard";
import { ThreadCard } from "../../components/ThreadCard";
import { useCategories } from "../../hooks/useCategories";
import { useCurrency } from "../../hooks/useCurrency";
import { useItems } from "../../hooks/useItems";
import { useCreateSetup, useSetups } from "../../hooks/useSetups";
import { useThreads } from "../../hooks/useThreads";
import { useTotals } from "../../hooks/useTotals";
import { useWeightUnit } from "../../hooks/useWeightUnit";
import { formatPrice, formatWeight } from "../../lib/formatters";
import { LucideIcon } from "../../lib/iconData";
import { useUIStore } from "../../stores/uiStore";

const searchSchema = z.object({
	tab: z.enum(["gear", "planning", "setups"]).catch("gear"),
});

export const Route = createFileRoute("/collection/")({
	validateSearch: searchSchema,
	component: CollectionPage,
});

const TAB_ORDER = ["gear", "planning", "setups"] as const;

const slideVariants = {
	enter: (dir: number) => ({ x: `${dir * 15}%`, opacity: 0 }),
	center: { x: 0, opacity: 1 },
	exit: (dir: number) => ({ x: `${dir * -15}%`, opacity: 0 }),
};

function CollectionPage() {
	const { tab } = Route.useSearch();
	const prevTab = useRef(tab);

	const direction =
		TAB_ORDER.indexOf(tab) >= TAB_ORDER.indexOf(prevTab.current) ? 1 : -1;
	prevTab.current = tab;

	return (
		<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 overflow-x-hidden">
			<AnimatePresence mode="wait" initial={false} custom={direction}>
				<motion.div
					key={tab}
					custom={direction}
					variants={slideVariants}
					initial="enter"
					animate="center"
					exit="exit"
					transition={{ duration: 0.12, ease: "easeInOut" }}
				>
					{tab === "gear" ? (
						<CollectionView />
					) : tab === "planning" ? (
						<PlanningView />
					) : (
						<SetupsView />
					)}
				</motion.div>
			</AnimatePresence>
		</div>
	);
}

function CollectionView() {
	const { data: items, isLoading: itemsLoading } = useItems();
	const { data: totals } = useTotals();
	const { data: categories } = useCategories();
	const unit = useWeightUnit();
	const currency = useCurrency();
	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">
								{formatWeight(totals.global.totalWeight, unit)}
							</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">
								{formatPrice(totals.global.totalCost, currency)}
							</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}
								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}
											categoryName={categoryName}
											categoryIcon={categoryIcon}
											imageFilename={item.imageFilename}
											productUrl={item.productUrl}
										/>
									))}
								</div>
							</div>
						);
					},
				)
			)}
		</>
	);
}

function PlanningView() {
	const [activeTab, setActiveTab] = useState<"active" | "resolved">("active");
	const [categoryFilter, setCategoryFilter] = useState<number | null>(null);

	const openCreateThreadModal = useUIStore((s) => s.openCreateThreadModal);
	const { data: categories } = useCategories();
	const { data: threads, isLoading } = useThreads(activeTab === "resolved");

	if (isLoading) {
		return (
			<div className="animate-pulse space-y-4">
				{[1, 2].map((i) => (
					<div key={i} className="h-24 bg-gray-200 rounded-xl" />
				))}
			</div>
		);
	}

	// Filter threads by active tab and category
	const filteredThreads = (threads ?? [])
		.filter((t) => t.status === activeTab)
		.filter((t) => (categoryFilter ? t.categoryId === categoryFilter : true));

	// Determine if we should show the educational empty state
	const isEmptyNoFilters =
		filteredThreads.length === 0 &&
		activeTab === "active" &&
		categoryFilter === null &&
		(!threads || threads.length === 0);

	return (
		<div>
			{/* Header row */}
			<div className="flex items-center justify-between mb-4">
				<h2 className="text-lg font-semibold text-gray-900">
					Planning Threads
				</h2>
				<button
					type="button"
					onClick={openCreateThreadModal}
					className="inline-flex items-center gap-2 px-4 py-2 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>
					New Thread
				</button>
			</div>

			{/* Filter row */}
			<div className="flex items-center justify-between mb-6">
				{/* Pill tabs */}
				<div className="flex bg-gray-100 rounded-full p-0.5 gap-0.5">
					<button
						type="button"
						onClick={() => setActiveTab("active")}
						className={`px-4 py-1.5 text-sm font-medium rounded-full transition-colors ${
							activeTab === "active"
								? "bg-gray-700 text-white"
								: "text-gray-600 hover:bg-gray-200"
						}`}
					>
						Active
					</button>
					<button
						type="button"
						onClick={() => setActiveTab("resolved")}
						className={`px-4 py-1.5 text-sm font-medium rounded-full transition-colors ${
							activeTab === "resolved"
								? "bg-gray-700 text-white"
								: "text-gray-600 hover:bg-gray-200"
						}`}
					>
						Resolved
					</button>
				</div>

				{/* Category filter */}
				<CategoryFilterDropdown
					value={categoryFilter}
					onChange={setCategoryFilter}
					categories={categories ?? []}
				/>
			</div>

			{/* Content: empty state or thread grid */}
			{isEmptyNoFilters ? (
				<div className="py-16">
					<div className="max-w-lg mx-auto text-center">
						<h2 className="text-xl font-semibold text-gray-900 mb-8">
							Plan your next purchase
						</h2>
						<div className="space-y-6 text-left mb-10">
							<div className="flex items-start gap-4">
								<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-700 font-bold text-sm shrink-0">
									1
								</div>
								<div>
									<p className="font-medium text-gray-900">Create a thread</p>
									<p className="text-sm text-gray-500">
										Start a research thread for gear you're considering
									</p>
								</div>
							</div>
							<div className="flex items-start gap-4">
								<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-700 font-bold text-sm shrink-0">
									2
								</div>
								<div>
									<p className="font-medium text-gray-900">Add candidates</p>
									<p className="text-sm text-gray-500">
										Add products you're comparing with prices and weights
									</p>
								</div>
							</div>
							<div className="flex items-start gap-4">
								<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-700 font-bold text-sm shrink-0">
									3
								</div>
								<div>
									<p className="font-medium text-gray-900">Pick a winner</p>
									<p className="text-sm text-gray-500">
										Resolve the thread and the winner joins your collection
									</p>
								</div>
							</div>
						</div>
						<button
							type="button"
							onClick={openCreateThreadModal}
							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>
							Create your first thread
						</button>
					</div>
				</div>
			) : filteredThreads.length === 0 ? (
				<div className="py-12 text-center">
					<p className="text-sm text-gray-500">No threads found</p>
				</div>
			) : (
				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
					{filteredThreads.map((thread) => (
						<ThreadCard
							key={thread.id}
							id={thread.id}
							name={thread.name}
							candidateCount={thread.candidateCount}
							minPriceCents={thread.minPriceCents}
							maxPriceCents={thread.maxPriceCents}
							createdAt={thread.createdAt}
							status={thread.status}
							categoryName={thread.categoryName}
							categoryIcon={thread.categoryIcon}
						/>
					))}
				</div>
			)}

			<CreateThreadModal />
		</div>
	);
}

function SetupsView() {
	const [newSetupName, setNewSetupName] = useState("");
	const { data: setups, isLoading } = useSetups();
	const createSetup = useCreateSetup();

	function handleCreateSetup(e: React.FormEvent) {
		e.preventDefault();
		const name = newSetupName.trim();
		if (!name) return;
		createSetup.mutate({ name }, { onSuccess: () => setNewSetupName("") });
	}

	return (
		<div>
			{/* Create setup form */}
			<form onSubmit={handleCreateSetup} className="flex gap-2 mb-6">
				<input
					type="text"
					value={newSetupName}
					onChange={(e) => setNewSetupName(e.target.value)}
					placeholder="New setup name..."
					className="flex-1 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"
				/>
				<button
					type="submit"
					disabled={!newSetupName.trim() || createSetup.isPending}
					className="px-4 py-2 bg-gray-700 hover:bg-gray-800 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
				>
					{createSetup.isPending ? "Creating..." : "Create"}
				</button>
			</form>

			{/* Loading skeleton */}
			{isLoading && (
				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
					{[1, 2].map((i) => (
						<div
							key={i}
							className="h-24 bg-gray-200 rounded-xl animate-pulse"
						/>
					))}
				</div>
			)}

			{/* Empty state */}
			{!isLoading && (!setups || setups.length === 0) && (
				<div className="py-16">
					<div className="max-w-lg mx-auto text-center">
						<h2 className="text-xl font-semibold text-gray-900 mb-8">
							Build your perfect loadout
						</h2>
						<div className="space-y-6 text-left mb-10">
							<div className="flex items-start gap-4">
								<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-700 font-bold text-sm shrink-0">
									1
								</div>
								<div>
									<p className="font-medium text-gray-900">Create a setup</p>
									<p className="text-sm text-gray-500">
										Name your loadout for a specific trip or activity
									</p>
								</div>
							</div>
							<div className="flex items-start gap-4">
								<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-700 font-bold text-sm shrink-0">
									2
								</div>
								<div>
									<p className="font-medium text-gray-900">Add items</p>
									<p className="text-sm text-gray-500">
										Pick gear from your collection to include in the setup
									</p>
								</div>
							</div>
							<div className="flex items-start gap-4">
								<div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-700 font-bold text-sm shrink-0">
									3
								</div>
								<div>
									<p className="font-medium text-gray-900">Track weight</p>
									<p className="text-sm text-gray-500">
										See weight breakdown and optimize your pack
									</p>
								</div>
							</div>
						</div>
					</div>
				</div>
			)}

			{/* Setup grid */}
			{!isLoading && setups && setups.length > 0 && (
				<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
					{setups.map((setup) => (
						<SetupCard
							key={setup.id}
							id={setup.id}
							name={setup.name}
							itemCount={setup.itemCount}
							totalWeight={setup.totalWeight}
							totalCost={setup.totalCost}
						/>
					))}
				</div>
			)}
		</div>
	);
}
