"use client";

import React, { memo, useEffect, useRef } from "react";
import { FaSearch } from "react-icons/fa";
import { IoClose } from "react-icons/io5";
import { Badge } from "./ui/badge";
import { Input } from "./ui/input";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { formatCurrency } from "@/lib/utils";

import useSearch from "@/hooks/use-search";

interface SearchComponentProps {
  maxHeight?: string;
  onProductClick?: () => void;
}

/**
 * Lightweight search result card.
 * Does NOT use ProductCard to avoid mounting FavouriteButton (which triggers wishlist API calls).
 */
const SearchResultCard = memo(function SearchResultCard({
  product,
  locale,
  onClick,
}: {
  product: any;
  locale: string;
  onClick?: () => void;
}) {
  const productId = product?.entityId || product?.product_id || product?.id;
  const name = product?.name || "";
  const truncatedName = name.length > 30 ? name.slice(0, 30) + "..." : name;
  const imageUrl =
    product?.thumbNail ||
    product?.base_image?.original_image_url ||
    product?.base_image?.url ||
    product?.images?.[0]?.url ||
    "/images/card-image.png";

  const specialPrice = product?.special_price
    ? Number(product.special_price)
    : null;
  const rawPrice = Number(product?.price) || 0;
  const price = specialPrice && specialPrice > 0 ? specialPrice : rawPrice;
  const formattedPrice =
    product?.formattedFinalPrice ||
    product?.formatedSpecialPrice ||
    product?.formatted_price ||
    `${price} SAR`;

  const displayPrice = formatCurrency(price, locale);

  return (
    <Link
      href={`/${locale}/product/${productId}`}
      onClick={onClick}
      className="flex flex-col bg-white rounded-xl border border-gray-100 overflow-hidden hover:shadow-md transition-shadow cursor-pointer"
     
    >
      {/* Image */}
      <div className="relative w-full aspect-square bg-gray-50 overflow-hidden">
        <Image
          src={imageUrl}
          alt={truncatedName || "منتج"}
          fill
          sizes="(max-width: 640px) 50vw, 25vw"
          className="object-contain p-2"
        />
      </div>

      {/* Info */}
      <div className="p-2 flex flex-col gap-1">
        <p className="text-[13px] font-semibold text-gray-800 line-clamp-1">
          {truncatedName || "منتج"}
        </p>
        <p className="text-[14px] font-bold text-gray-900">
          {typeof formattedPrice === "string"
            ? formattedPrice.replace(/\.00(\s|$)/, "$1")
            : displayPrice}
        </p>
      </div>
    </Link>
  );
});

/**
 * Product search and filter component.
 * Uses lightweight cards instead of full ProductCard to avoid
 * re-rendering issues from FavouriteButton/useFavourites hooks.
 */
const SearchComponent: React.FC<SearchComponentProps> = ({ maxHeight, onProductClick }) => {
  const {
    isLoading,
    t,
    search,
    setSearch,
    categories,
    categoryIndex,
    setSearchCategory,
    setCategoryIndex,
    searchCategory,
    filteredProducts,
  } = useSearch();

  const pathname = usePathname();
  const locale = pathname?.split("/")[1] || "ar";

  // Auto-close the search dialog when the route changes (user clicked a product)
  const prevPathRef = useRef(pathname);
  useEffect(() => {
    if (prevPathRef.current !== pathname) {
      prevPathRef.current = pathname;
      onProductClick?.();
    }
  }, [pathname, onProductClick]);

  /** Reset all filters */
  const handleClearFilters = () => {
    setSearch("");
    setSearchCategory("");
    setCategoryIndex(null);
  };

  /** Reset filters and close search when clicking a product link */
  const handleProductClick = () => {
    handleClearFilters();
    onProductClick?.();
  };

  /** Category list — from home data */
  const categoryList: any[] = Array.isArray(categories) ? categories : [];

  return (
    <div
      className={`w-full flex flex-col gap-4 py-3 overflow-hidden ${
        maxHeight ?? "rounded-md"
      }`}
    >
      {/* 🔍 Search Input */}
      <div className="w-full relative mt-2">
        <Input
          type="text"
          placeholder={t("search-placeholder")}
          className="w-full pr-8"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        {isLoading ? (
          <div className="absolute ltr:right-2 rtl:left-2 top-1/2 -translate-y-1/2">
            <div className="w-4 h-4 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin" />
          </div>
        ) : (
          <FaSearch className="absolute ltr:right-2 rtl:left-2 top-1/2 -translate-y-1/2 text-gray-500 text-sm pointer-events-none" />
        )}
      </div>



      {/* ❌ Clear Filters */}
      {(searchCategory || search) && (
        <button
          onClick={handleClearFilters}
          className="flex items-center gap-2 w-fit bg-red-500 text-white px-3 py-1 rounded-md text-sm hover:bg-red-600 transition-colors"
        >
          {t("clear-filters")}
          <IoClose className="text-lg font-bold" />
        </button>
      )}

      {/* 🛍️ Products Grid — uses lightweight cards, NOT ProductCard */}
      <div className="w-full grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3 overflow-y-auto overflow-x-hidden max-h-[55vh]">
        {filteredProducts.length > 0 ? (
          filteredProducts.slice(0, 12).map((product: any, index: number) => (
            <SearchResultCard
              key={product?.id ?? product?.entityId ?? index}
              product={product}
              locale={locale}
              onClick={handleProductClick}
            />
          ))
        ) : isLoading ? (
          <div className="col-span-2 sm:col-span-3 lg:col-span-4 flex items-center justify-center py-12">
            <div className="w-8 h-8 border-3 border-gray-300 border-t-gray-600 rounded-full animate-spin" />
          </div>
        ) : (
          <p className="col-span-2 sm:col-span-3 lg:col-span-4 text-center text-gray-500 mt-8">
            {t("no-results-found")}
          </p>
        )}
      </div>
    </div>
  );
};

export default SearchComponent;
