import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { CategoryPicker } from "../../components/CategoryPicker";
import { GearImage, imageContainerBg } from "../../components/GearImage";
import { ImageCropEditor } from "../../components/ImageCropEditor";
import { ImageUpload } from "../../components/ImageUpload";
import { useFormatters } from "../../hooks/useFormatters";
import { useDuplicateItem, useItem, useUpdateItem } from "../../hooks/useItems";
import { LucideIcon } from "../../lib/iconData";
import { useUIStore } from "../../stores/uiStore";

export const Route = createFileRoute("/items/$itemId")({
	component: ItemDetail,
});

interface EditFormState {
	name: string;
	brand: string;
	weightGrams: string;
	priceDollars: string;
	quantity: number;
	categoryId: number;
	notes: string;
	productUrl: string;
	imageFilename: string | null;
}

function ItemDetail() {
	const { itemId } = Route.useParams();
	const navigate = useNavigate();
	const {
		data: item,
		isLoading,
		error,
	} = useItem(Number(itemId)) as ReturnType<typeof useItem> & {
		data:
			| (NonNullable<ReturnType<typeof useItem>["data"]> & {
					imageUrl?: string | null;
			  })
			| undefined;
	};
	const { weight, price } = useFormatters();
	const updateItem = useUpdateItem();
	const duplicateItem = useDuplicateItem();
	const openConfirmDelete = useUIStore((s) => s.openConfirmDelete);
	const openExternalLink = useUIStore((s) => s.openExternalLink);

	const [isEditing, setIsEditing] = useState(false);
	const [editingCrop, setEditingCrop] = useState(false);
	const [form, setForm] = useState<EditFormState>({
		name: "",
		brand: "",
		weightGrams: "",
		priceDollars: "",
		quantity: 1,
		categoryId: 0,
		notes: "",
		productUrl: "",
		imageFilename: null,
	});

	function enterEditMode() {
		if (!item) return;
		setForm({
			name: item.brand ? item.name.replace(`${item.brand} `, "") : item.name,
			brand: item.brand || "",
			weightGrams: item.weightGrams != null ? String(item.weightGrams) : "",
			priceDollars:
				item.priceCents != null ? (item.priceCents / 100).toFixed(2) : "",
			quantity: item.quantity,
			categoryId: item.categoryId,
			notes: item.notes || "",
			productUrl: item.productUrl || "",
			imageFilename: item.imageFilename,
		});
		setIsEditing(true);
	}

	function cancelEdit() {
		setIsEditing(false);
	}

	function handleSave() {
		if (!item) return;
		const hasGlobalItem = !!(item as Record<string, unknown>).globalItemId;

		// Personal fields (always editable)
		const payload: Record<string, unknown> = {
			id: item.id,
			quantity: form.quantity,
			categoryId: form.categoryId,
			notes: form.notes.trim() || undefined,
			productUrl: form.productUrl.trim() || undefined,
			imageFilename: form.imageFilename ?? undefined,
		};

		// Global fields (only editable for standalone items)
		if (!hasGlobalItem) {
			const weightGrams = form.weightGrams.trim()
				? Math.round(Number(form.weightGrams))
				: null;
			const priceCents = form.priceDollars.trim()
				? Math.round(Number(form.priceDollars) * 100)
				: null;
			const brandTrimmed = form.brand.trim();
			const nameTrimmed = form.name.trim();
			const fullName = brandTrimmed
				? `${brandTrimmed} ${nameTrimmed}`
				: nameTrimmed;

			payload.name = fullName;
			payload.brand = brandTrimmed || undefined;
			payload.weightGrams = weightGrams ?? undefined;
			payload.priceCents = priceCents ?? undefined;
		}

		updateItem.mutate(payload as Parameters<typeof updateItem.mutate>[0], {
			onSuccess: () => setIsEditing(false),
		});
	}

	function handleDuplicate() {
		if (!item) return;
		duplicateItem.mutate(item.id, {
			onSuccess: (newItem) => {
				navigate({
					to: "/items/$itemId",
					params: { itemId: String(newItem.id) },
				});
			},
		});
	}

	function handleDelete() {
		if (!item) return;
		openConfirmDelete(item.id);
	}

	if (isLoading) {
		return (
			<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
				<div className="animate-pulse space-y-6">
					<div className="h-4 bg-gray-100 rounded w-24" />
					<div className="aspect-[4/3] bg-gray-100 rounded-xl" />
					<div className="space-y-3">
						<div className="h-8 bg-gray-100 rounded w-64" />
						<div className="flex gap-2">
							<div className="h-7 bg-gray-100 rounded-full w-20" />
							<div className="h-7 bg-gray-100 rounded-full w-20" />
							<div className="h-7 bg-gray-100 rounded-full w-28" />
						</div>
						<div className="h-4 bg-gray-100 rounded w-full" />
						<div className="h-4 bg-gray-100 rounded w-3/4" />
					</div>
				</div>
			</div>
		);
	}

	if (error || !item) {
		return (
			<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
				<Link
					to="/collection"
					className="text-sm text-gray-400 hover:text-gray-600 transition-colors"
				>
					&larr; Back to collection
				</Link>
				<div className="text-center py-16">
					<p className="text-sm text-gray-500">Item not found</p>
				</div>
			</div>
		);
	}

	const imageUrl = item.imageUrl || null;
	const isReference = !!(item as Record<string, unknown>).globalItemId;

	return (
		<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
			{/* Top bar */}
			<div className="flex items-center justify-between mb-6">
				<Link
					to="/collection"
					className="text-sm text-gray-400 hover:text-gray-600 transition-colors"
				>
					&larr; Back to collection
				</Link>
				{!isEditing && (
					<div className="flex items-center gap-2">
						{/* Duplicate — desktop */}
						<button
							type="button"
							onClick={handleDuplicate}
							disabled={duplicateItem.isPending}
							className="hidden md:inline-flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
						>
							Duplicate
						</button>
						{/* Duplicate — mobile */}
						<button
							type="button"
							onClick={handleDuplicate}
							disabled={duplicateItem.isPending}
							className="md:hidden inline-flex items-center justify-center min-w-[44px] min-h-[44px] p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
							aria-label="Duplicate"
							title="Duplicate"
						>
							<LucideIcon name="copy" size={16} />
						</button>
						{/* Delete — desktop */}
						<button
							type="button"
							onClick={handleDelete}
							className="hidden md:inline-flex items-center gap-1.5 px-3 py-1.5 text-sm text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
						>
							{isReference ? "Remove from Collection" : "Delete"}
						</button>
						{/* Delete — mobile */}
						<button
							type="button"
							onClick={handleDelete}
							className="md:hidden inline-flex items-center justify-center min-w-[44px] min-h-[44px] p-2 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
							aria-label={isReference ? "Remove from Collection" : "Delete"}
							title={isReference ? "Remove from Collection" : "Delete"}
						>
							<LucideIcon name="trash-2" size={16} />
						</button>
						{/* Edit — desktop */}
						<button
							type="button"
							onClick={enterEditMode}
							className="hidden md:inline-flex items-center gap-1.5 px-4 py-1.5 text-sm font-medium text-white bg-gray-700 hover:bg-gray-800 rounded-lg transition-colors"
						>
							Edit
						</button>
						{/* Edit — mobile */}
						<button
							type="button"
							onClick={enterEditMode}
							className="md:hidden inline-flex items-center justify-center min-w-[44px] min-h-[44px] p-2 text-white bg-gray-700 hover:bg-gray-800 rounded-lg transition-colors"
							aria-label="Edit"
							title="Edit"
						>
							<LucideIcon name="pencil" size={16} />
						</button>
					</div>
				)}
				{isEditing && (
					<div className="flex items-center gap-2">
						<button
							type="button"
							onClick={cancelEdit}
							className="px-3 py-1.5 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
						>
							Cancel
						</button>
						<button
							type="button"
							onClick={handleSave}
							disabled={updateItem.isPending || !form.name.trim()}
							className="px-4 py-1.5 text-sm font-medium text-white bg-gray-700 hover:bg-gray-800 rounded-lg transition-colors disabled:opacity-50"
						>
							{updateItem.isPending ? "Saving..." : "Save"}
						</button>
					</div>
				)}
			</div>

			{/* Hero image */}
			{isEditing && !isReference ? (
				<div className="mb-6">
					<ImageUpload
						value={form.imageFilename}
						imageUrl={imageUrl}
						dominantColor={item.dominantColor}
						onChange={(filename, dominantColor) => {
							setForm((f) => ({ ...f, imageFilename: filename }));
							if (dominantColor) {
								updateItem.mutate({
									id: item.id,
									dominantColor,
								});
							}
						}}
						onCropChange={(crop) => {
							updateItem.mutate({
								id: item.id,
								cropZoom: crop.zoom,
								cropX: crop.x,
								cropY: crop.y,
							});
						}}
					/>
				</div>
			) : editingCrop && imageUrl ? (
				<div className="mb-6">
					<ImageCropEditor
						imageUrl={imageUrl}
						dominantColor={item.dominantColor}
						initialZoom={item.cropZoom ?? 1}
						initialX={item.cropX ?? 0}
						initialY={item.cropY ?? 0}
						aspect={4 / 3}
						onSave={(crop) => {
							updateItem.mutate({
								id: item.id,
								cropZoom: crop.zoom,
								cropX: crop.x,
								cropY: crop.y,
							});
							setEditingCrop(false);
						}}
						onCancel={() => setEditingCrop(false)}
					/>
				</div>
			) : (
				<div
					className="aspect-[4/3] rounded-xl overflow-hidden mb-2"
					style={{
						backgroundColor: imageUrl
							? imageContainerBg(item.dominantColor)
							: undefined,
					}}
				>
					{imageUrl ? (
						<GearImage
							src={imageUrl}
							alt={item.name}
							dominantColor={item.dominantColor}
							cropZoom={item.cropZoom}
							cropX={item.cropX}
							cropY={item.cropY}
						/>
					) : (
						<div className="w-full h-full bg-gray-50 flex flex-col items-center justify-center">
							<LucideIcon
								name={item.categoryIcon}
								size={64}
								className="text-gray-300"
							/>
						</div>
					)}
				</div>
			)}

			{/* Header / Name */}
			<div className="mb-4">
				{isEditing ? (
					isReference ? (
						/* Reference items: name/brand are read-only (from global catalog) */
						<>
							{item.brand && (
								<p className="text-sm font-medium text-gray-400 uppercase tracking-wide mb-1">
									{item.brand}
								</p>
							)}
							<h1 className="text-2xl font-bold text-gray-900">
								{item.brand
									? item.name.replace(`${item.brand} `, "")
									: item.name}
							</h1>
							<p className="text-xs text-gray-400 mt-1">
								Name and brand are from the catalog
							</p>
						</>
					) : (
						<div className="space-y-2">
							<input
								type="text"
								value={form.brand}
								onChange={(e) =>
									setForm((f) => ({ ...f, brand: e.target.value }))
								}
								className="w-full text-sm font-medium text-gray-500 border border-gray-200 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
								placeholder="Brand / Manufacturer (optional)"
							/>
							<input
								type="text"
								value={form.name}
								onChange={(e) =>
									setForm((f) => ({ ...f, name: e.target.value }))
								}
								className="w-full text-2xl font-bold text-gray-900 border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
								placeholder="Item name / Model"
							/>
						</div>
					)
				) : (
					<>
						{item.brand && (
							<p className="text-sm font-medium text-gray-400 uppercase tracking-wide mb-1">
								{item.brand}
							</p>
						)}
						<h1 className="text-2xl font-bold text-gray-900">
							{item.brand ? item.name.replace(`${item.brand} `, "") : item.name}
						</h1>
					</>
				)}
			</div>

			{/* Badges / Specs */}
			{isEditing ? (
				<div className="grid grid-cols-2 gap-4 mb-6">
					{isReference ? (
						/* Reference items: weight/price are read-only (from catalog) */
						<>
							{item.weightGrams != null && (
								<div>
									<label className="block text-xs font-medium text-gray-500 mb-1">
										Weight (g)
									</label>
									<p className="py-2 px-3 bg-gray-50 border border-gray-100 rounded-lg text-sm text-gray-500">
										{item.weightGrams}
									</p>
								</div>
							)}
							{item.priceCents != null && (
								<div>
									<label className="block text-xs font-medium text-gray-500 mb-1">
										MSRP
									</label>
									<p className="py-2 px-3 bg-gray-50 border border-gray-100 rounded-lg text-sm text-gray-500">
										{price(item.priceCents)}
									</p>
								</div>
							)}
						</>
					) : (
						<>
							<div>
								<label className="block text-xs font-medium text-gray-500 mb-1">
									Weight (g)
								</label>
								<input
									type="number"
									value={form.weightGrams}
									onChange={(e) =>
										setForm((f) => ({
											...f,
											weightGrams: e.target.value,
										}))
									}
									className="w-full py-2 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
									placeholder="0"
								/>
							</div>
							<div>
								<label className="block text-xs font-medium text-gray-500 mb-1">
									Price ($)
								</label>
								<input
									type="number"
									step="0.01"
									value={form.priceDollars}
									onChange={(e) =>
										setForm((f) => ({
											...f,
											priceDollars: e.target.value,
										}))
									}
									className="w-full py-2 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
									placeholder="0.00"
								/>
							</div>
						</>
					)}
					<div>
						<label className="block text-xs font-medium text-gray-500 mb-1">
							Quantity
						</label>
						<input
							type="number"
							min={1}
							value={form.quantity}
							onChange={(e) =>
								setForm((f) => ({
									...f,
									quantity: Math.max(1, Number(e.target.value)),
								}))
							}
							className="w-full py-2 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
						/>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-500 mb-1">
							Category
						</label>
						<CategoryPicker
							value={form.categoryId}
							onChange={(id) => setForm((f) => ({ ...f, categoryId: id }))}
						/>
					</div>
				</div>
			) : (
				<div className="flex flex-wrap gap-2 mb-6">
					{item.weightGrams != null && (
						<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-50 text-blue-500">
							{weight(item.weightGrams)}
						</span>
					)}
					{item.priceCents != null && (
						<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-50 text-green-500">
							{price(item.priceCents)}
						</span>
					)}
					<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium bg-gray-50 text-gray-600">
						<LucideIcon
							name={item.categoryIcon}
							size={14}
							className="text-gray-400"
						/>
						{item.categoryName}
					</span>
					{item.quantity > 1 && (
						<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-50 text-purple-500">
							Qty: {item.quantity}
						</span>
					)}
				</div>
			)}

			{/* Notes */}
			{isEditing ? (
				<div className="mb-6">
					<label className="block text-xs font-medium text-gray-500 mb-1">
						Notes
					</label>
					<textarea
						value={form.notes}
						onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
						rows={4}
						className="w-full py-2 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent resize-none"
						placeholder="Add notes..."
					/>
				</div>
			) : (
				item.notes && (
					<div className="mb-6">
						<h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide mb-2">
							Notes
						</h2>
						<p className="text-gray-600 text-sm leading-relaxed">
							{item.notes}
						</p>
					</div>
				)
			)}

			{/* Product URL */}
			{isEditing ? (
				<div className="mb-6">
					<label className="block text-xs font-medium text-gray-500 mb-1">
						Product URL
					</label>
					<input
						type="url"
						value={form.productUrl}
						onChange={(e) =>
							setForm((f) => ({
								...f,
								productUrl: e.target.value,
							}))
						}
						className="w-full py-2 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 focus:border-transparent"
						placeholder="https://..."
					/>
				</div>
			) : (
				item.productUrl && (
					<div className="mb-6">
						<button
							type="button"
							onClick={() => openExternalLink(item.productUrl!)}
							className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-600 bg-gray-50 hover:bg-gray-100 rounded-lg 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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
								/>
							</svg>
							View product
						</button>
					</div>
				)
			)}

			{/* Metadata */}
			{!isEditing && (
				<div className="border-t border-gray-100 pt-4 mt-8">
					<div className="flex gap-6 text-xs text-gray-400">
						<span>
							Added{" "}
							{new Date(item.createdAt).toLocaleDateString(undefined, {
								year: "numeric",
								month: "short",
								day: "numeric",
							})}
						</span>
						<span>
							Updated{" "}
							{new Date(item.updatedAt).toLocaleDateString(undefined, {
								year: "numeric",
								month: "short",
								day: "numeric",
							})}
						</span>
					</div>
				</div>
			)}
		</div>
	);
}
