import React, { useState, useContext, useRef, useEffect } from "react";
import { Search } from "lucide-react";
import Link from "next/link";
import ProductContext from "@/app/contexts/productContext";
import { backendUrl } from "@/utils/axios";
import Image from "next/image";

const SearchComponent = ({ isScrolled }) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const { products, category } = useContext(ProductContext);
  const searchRef = useRef(null);

  const filteredProducts = products
    ?.filter((product) =>
      product.product_name.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .slice(0, 5);

  const filteredCategories = category
    ?.filter((category) =>
      category.category_name.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .slice(0, 3);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (searchRef.current && !searchRef.current.contains(event.target)) {
        setShowSuggestions(false);
        if (isScrolled) setIsExpanded(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [isScrolled]);

  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
    setShowSuggestions(true);
  };

  const SearchInput = () => (
    <div className="flex items-center border bg-white">
      <input
        type="text"
        value={searchTerm}
        onChange={handleSearchChange}
        onFocus={() => setShowSuggestions(true)}
        placeholder="Search products..."
        className="p-2 outline-none w-full"
      />
      <Search size={20} className="mx-2" />
    </div>
  );

  const Suggestions = () => {
    if (!showSuggestions || !searchTerm) return null;

    const hasResults =
      filteredCategories?.length > 0 || filteredProducts?.length > 0;

    return (
      <div className="absolute z-50 bg-white shadow-lg w-full mt-2 rounded-md overflow-hidden">
        {!hasResults && searchTerm && (
          <div className="p-4 text-center text-gray-500">No results found</div>
        )}

        {filteredCategories?.length > 0 && (
          <div className="border-b">
            <div className="p-2 bg-gray-50 text-sm font-medium">Categories</div>
            {filteredCategories.map((category) => (
              <Link
                key={category.id}
                href={`/collections/${category.id}`}
                className="block p-2 hover:bg-gray-50"
                onClick={() => {
                  setShowSuggestions(false);
                  setIsExpanded(false);
                }}
              >
                {category.category_name}
              </Link>
            ))}
          </div>
        )}

        {filteredProducts?.length > 0 && (
          <div>
            <div className="p-2 bg-gray-50 text-sm font-medium">Products</div>
            {filteredProducts.map((product) => (
              <Link
                key={product.id}
                href={`/products/${product.id}`}
                className="block p-2 hover:bg-gray-50"
                onClick={() => {
                  setShowSuggestions(false);
                  setIsExpanded(false);
                }}
              >
                <div className="flex items-center gap-2">
                  {product.images?.[0] && (
                    <Image
                      src={`${backendUrl}${product.images[0].image}`}
                      alt={product.product_name}
                      width={32}
                      height={32}
                      className="object-cover"
                    />
                  )}
                  <span>{product.product_name}</span>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div ref={searchRef} className="relative">
      {isScrolled ? (
        <>
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="cursor-pointer"
          >
            <Search size={20} />
          </button>
          {isExpanded && (
            <div className="absolute right-[-10rem] top-12 bg-white shadow-lg w-72 p-4">
              <SearchInput />
              <Suggestions />
            </div>
          )}
        </>
      ) : (
        <div className="w-64">
          <SearchInput />
          <Suggestions />
        </div>
      )}
    </div>
  );
};

export default SearchComponent;
