"use client";

import Image from "next/image";
import Link from "next/link";
import { formatPrice } from "@repo/utils";
import { getProductUrl } from "@/lib/shop/productMapper";
import type { SearchResultItem as SearchResultItemType } from "@/lib/search/types";

function formatSlugLabel(slug: string): string {
  return slug
    .split("-")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
}

interface SearchResultItemProps {
  item: SearchResultItemType;
  index: number;
  isSelected: boolean;
  onSelect: () => void;
  onMouseEnter: () => void;
}

export function SearchResultItem({
  item,
  index,
  isSelected,
  onSelect,
  onMouseEnter,
}: SearchResultItemProps) {
  const hasSale =
    item.compareAtPrice != null && item.compareAtPrice > item.minPrice;

  const breadcrumb = `${formatSlugLabel(item.parentCategorySlug)} › ${formatSlugLabel(item.childCategorySlug)}`;

  return (
    <Link
      href={getProductUrl(item)}
      id={`search-result-${index}`}
      role="option"
      aria-selected={isSelected}
      onClick={onSelect}
      onMouseEnter={onMouseEnter}
      className={`flex min-h-[56px] items-center gap-3 px-3 py-2 transition-colors md:min-h-[48px] ${
        isSelected ? "bg-[#e8f7f6]" : "hover:bg-[#f5fafa]"
      }`}
    >
      {/* Thumbnail */}
      <div className="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-[#f0f8f7]">
        <Image
          src={item.imageUrl ?? "/images/placeholder-product.png"}
          alt={item.imageAlt ?? item.name}
          fill
          className="object-cover"
          sizes="48px"
        />
      </div>

      {/* Name + meta */}
      <div className="min-w-0 flex-1">
        <p className="line-clamp-1 text-sm font-medium text-[#1a2e2d]">
          {item.name}
        </p>
        <p className="truncate text-xs text-[#8aa9a8]">{breadcrumb}</p>
        {item.brand && (
          <p className="truncate text-xs text-[#8aa9a8]">{item.brand}</p>
        )}
      </div>

      {/* Price */}
      <div className="shrink-0 text-right">
        {hasSale ? (
          <>
            <p className="text-xs text-[#8aa9a8] line-through">
              {formatPrice(item.compareAtPrice!)}
            </p>
            <p className="text-sm font-semibold text-[#f2705a]">
              {formatPrice(item.minPrice)}
            </p>
          </>
        ) : item.minPrice > 0 ? (
          <p className="text-sm font-semibold text-[#236f6b]">
            {formatPrice(item.minPrice)}
          </p>
        ) : null}
      </div>
    </Link>
  );
}
