import { Reorder } from "framer-motion";
import { useRef } from "react";
import { useFormatters } from "../hooks/useFormatters";
import type { CandidateDelta } from "../hooks/useImpactDeltas";
import { LucideIcon } from "../lib/iconData";
import { useUIStore } from "../stores/uiStore";
import { ImpactDeltaBadge } from "./ImpactDeltaBadge";
import { StatusBadge } from "./StatusBadge";

interface CandidateWithCategory {
	id: number;
	threadId: number;
	name: string;
	weightGrams: number | null;
	priceCents: number | null;
	categoryId: number;
	notes: string | null;
	productUrl: string | null;
	imageFilename: string | null;
	status: "researching" | "ordered" | "arrived";
	pros: string | null;
	cons: string | null;
	createdAt: string;
	updatedAt: string;
	categoryName: string;
	categoryIcon: string;
}

interface CandidateListItemProps {
	candidate: CandidateWithCategory;
	rank: number;
	isActive: boolean;
	onStatusChange: (status: "researching" | "ordered" | "arrived") => void;
	delta?: CandidateDelta;
	onDragEnd?: () => void;
}

const RANK_COLORS = ["#D4AF37", "#C0C0C0", "#CD7F32"]; // gold, silver, bronze

export function RankBadge({ rank }: { rank: number }) {
	if (rank > 3) return null;
	return (
		<LucideIcon
			name="medal"
			size={16}
			className="shrink-0"
			style={{ color: RANK_COLORS[rank - 1] }}
		/>
	);
}

export function CandidateListItem({
	candidate,
	rank,
	isActive,
	onStatusChange,
	delta,
	onDragEnd,
}: CandidateListItemProps) {
	const isDragging = useRef(false);
	const { weight, price } = useFormatters();
	const openCandidateEditPanel = useUIStore((s) => s.openCandidateEditPanel);
	const openConfirmDeleteCandidate = useUIStore(
		(s) => s.openConfirmDeleteCandidate,
	);
	const openResolveDialog = useUIStore((s) => s.openResolveDialog);
	const openExternalLink = useUIStore((s) => s.openExternalLink);

	const sharedClassName =
		"flex items-center gap-3 bg-white rounded-xl border border-gray-100 p-3 hover:border-gray-200 hover:shadow-sm group cursor-default";

	const innerContent = (
		<>
			{/* Drag handle indicator */}
			{isActive && (
				<span className="text-gray-300 shrink-0">
					<LucideIcon name="grip-vertical" size={16} />
				</span>
			)}

			{/* Rank badge */}
			<RankBadge rank={rank} />

			{/* Image thumbnail */}
			<div className="w-12 h-12 rounded-lg overflow-hidden shrink-0 bg-gray-50 flex items-center justify-center">
				{candidate.imageFilename ? (
					<img
						src={`/uploads/${candidate.imageFilename}`}
						alt={candidate.name}
						className="w-full h-full object-cover"
					/>
				) : (
					<LucideIcon
						name={candidate.categoryIcon}
						size={20}
						className="text-gray-400"
					/>
				)}
			</div>

			{/* Name + badges */}
			<button
				type="button"
				onClick={() => {
					if (isDragging.current) return;
					openCandidateEditPanel(candidate.id);
				}}
				className="flex-1 min-w-0 text-left"
			>
				<p className="text-sm font-semibold text-gray-900 truncate">
					{candidate.name}
				</p>
				<div className="flex flex-wrap gap-1.5 mt-1">
					{candidate.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(candidate.weightGrams)}
						</span>
					)}
					<ImpactDeltaBadge delta={delta} type="weight" formatFn={weight} />
					{candidate.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(candidate.priceCents)}
						</span>
					)}
					<ImpactDeltaBadge delta={delta} type="price" formatFn={price} />
					<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={candidate.categoryIcon}
							size={14}
							className="inline-block mr-1 text-gray-500"
						/>
						{candidate.categoryName}
					</span>
					<StatusBadge
						status={candidate.status}
						onStatusChange={onStatusChange}
					/>
					{(candidate.pros || candidate.cons) && (
						<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-50 text-purple-700">
							+/- Notes
						</span>
					)}
				</div>
			</button>

			{/* Action buttons (hover-reveal) */}
			<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
				{isActive && (
					<button
						type="button"
						onClick={(e) => {
							e.stopPropagation();
							openResolveDialog(candidate.threadId, candidate.id);
						}}
						className="px-2 py-0.5 flex items-center gap-1 rounded-full text-xs font-medium bg-amber-100/90 text-amber-700 hover:bg-amber-200 cursor-pointer"
						title="Pick as winner"
					>
						<LucideIcon name="trophy" size={12} />
						Winner
					</button>
				)}
				{candidate.productUrl && (
					<button
						type="button"
						onClick={(e) => {
							e.stopPropagation();
							openExternalLink(candidate.productUrl as string);
						}}
						className="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 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>
					</button>
				)}
				<button
					type="button"
					onClick={(e) => {
						e.stopPropagation();
						openConfirmDeleteCandidate(candidate.id);
					}}
					className="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 cursor-pointer"
					title="Delete candidate"
				>
					<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>
				</button>
			</div>
		</>
	);

	// Reorder.Item requires a Reorder.Group parent — only use it in active threads
	if (isActive) {
		return (
			<Reorder.Item
				value={candidate}
				onDragStart={() => {
					isDragging.current = true;
				}}
				onDragEnd={() => {
					setTimeout(() => {
						isDragging.current = false;
					}, 0);
					onDragEnd?.();
				}}
				whileDrag={{ cursor: "grabbing" }}
				style={{ marginBottom: 8, cursor: "grab" }}
				className={sharedClassName}
			>
				{innerContent}
			</Reorder.Item>
		);
	}

	return <div className={sharedClassName}>{innerContent}</div>;
}
