"use client";

import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { Search, X, Loader2, CornerDownLeft } from "lucide-react";
import { searchProductsAction } from "@/actions/products/products.action";

interface SearchModalProps {
  isOpen: boolean;
  onClose: () => void;
}

interface ProductVariantResult {
  id: string;
  name: string;
  sku: string;
  slug: string;
  price: string;
  final_price: string;
  discount_type: string | null;
  discount_value: string;
  stock_count: number;
  in_stock: boolean;
  image_url: string | null;
  product_name: string;
  product_slug: string;
}

export default function SearchModal({ isOpen, onClose }: SearchModalProps) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<ProductVariantResult[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [loading, setLoading] = useState(false);
  const [debouncedQuery, setDebouncedQuery] = useState("");
  
  const inputRef = useRef<HTMLInputElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);

  // Focus input when modal opens
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
      setTimeout(() => {
        inputRef.current?.focus();
      }, 50);
    } else {
      document.body.style.overflow = "unset";
      setQuery("");
      setResults([]);
      setTotal(0);
      setPage(1);
      setPages(1);
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);



  // Handle keyboard events (ESC to close)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose]);

  // Click outside to close (handles clicks anywhere, including the navbar header)
  useEffect(() => {
    if (!isOpen) return;

    const handleOutsideClick = (e: MouseEvent) => {
      if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
        // Prevent closing immediately when clicking on a toggle button
        const isTrigger = (e.target as HTMLElement).closest('[aria-label="Search products"]');
        if (!isTrigger) {
          onClose();
        }
      }
    };

    document.addEventListener("mousedown", handleOutsideClick);
    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
    };
  }, [isOpen, onClose]);

  // Click outside to close (backup local click handler)
  const handleOverlayClick = (e: React.MouseEvent) => {
    if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
      onClose();
    }
  };

  // Debounce input (shortened to 75ms for instant snappy results)
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(query);
      setPage(1); // Reset page on query change
    }, 75);
    return () => clearTimeout(timer);
  }, [query]);

  // Fetch search results from backend via Server Action
  useEffect(() => {
    if (!isOpen) return;

    const fetchResults = async () => {
      if (!debouncedQuery.trim()) {
        setResults([]);
        setTotal(0);
        setPages(1);
        return;
      }

      setLoading(true);
      try {
        const res = await searchProductsAction(debouncedQuery, page, 5);
        if (res.success && res.data) {
          const searchPayload = res.data;
          setResults(searchPayload.data || []);
          setTotal(searchPayload.total || 0);
          setPages(searchPayload.pages || 1);
        } else {
          setResults([]);
          setTotal(0);
          setPages(1);
        }
      } catch (err) {
        console.error("Search failed:", err);
        setResults([]);
        setTotal(0);
        setPages(1);
      } finally {
        setLoading(false);
      }
    };

    fetchResults();
  }, [debouncedQuery, page, isOpen]);

  if (!isOpen) return null;

  const handleResultClick = (slug: string) => {
    router.push(`/products/${slug}`);
    onClose();
  };



  return (
    <div
      onClick={handleOverlayClick}
      className="fixed inset-0 z-40 flex items-start justify-center bg-black/60 p-4 pt-[12vh] animate-search-backdrop"
    >
      <div
        ref={modalRef}
        className="w-full max-w-2xl bg-zinc-950/90 border border-white/10 rounded-2xl shadow-[0_20px_50px_rgba(0,0,0,0.5)] overflow-hidden flex flex-col max-h-[80vh] animate-search-modal"
      >
        {/* Search header */}
        <div className="relative border-b border-white/10 flex items-center p-4">
          <Search className="w-5 h-5 text-zinc-400 mr-3 shrink-0" />
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search products by name, size, type, flavor..."
            className="w-full bg-transparent text-white text-base focus:outline-none placeholder-zinc-500"
          />
          {query && (
            <button
              onClick={() => setQuery("")}
              className="h-8 w-8 rounded-full bg-transparent hover:bg-white/5 text-zinc-400 hover:text-white transition-all duration-200 cursor-pointer flex items-center justify-center focus:outline-none mr-2"
              aria-label="Clear search"
            >
              <X className="w-4 h-4" />
            </button>
          )}
          <button
            onClick={onClose}
            className="h-9 w-9 rounded-full border border-white/10 hover:border-white/20 bg-transparent hover:bg-white/5 text-zinc-400 hover:text-brand-accent transition-all duration-200 cursor-pointer flex items-center justify-center focus:outline-none shrink-0 aspect-square"
            aria-label="Close search"
            title="Close Search (Esc)"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Results / Suggestion Body */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-[150px]">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-10 space-y-3 text-zinc-400">
              <Loader2 className="w-8 h-8 animate-spin text-brand-accent" />
              <p className="text-xs uppercase tracking-widest animate-pulse font-bold">Searching Products...</p>
            </div>
          ) : !query.trim() ? (
            <div className="flex flex-col items-center justify-center py-10 text-center text-zinc-500">
              <Search className="w-8 h-8 mb-2 stroke-1" />
              <p className="text-xs uppercase tracking-wider font-bold">Start typing to search products...</p>
            </div>
          ) : results.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-10 space-y-2 text-center">
              <p className="text-sm font-semibold text-zinc-400">No products match &quot;{query}&quot;</p>
              <p className="text-xs text-zinc-600">Try searching for a different size, weight, name, or flavor.</p>
            </div>
          ) : (
            <div className="space-y-3">
              <div className="flex justify-between items-center text-[10px] uppercase tracking-wider font-black text-brand-accent border-b border-white/5 pb-1">
                <span>Matching Products</span>
                <span>{total} matches found</span>
              </div>
              <div className="space-y-2">
                {results.map((product) => {
                  const hasDiscount =
                    product.discount_type &&
                    parseFloat(product.discount_value) > 0 &&
                    parseFloat(product.final_price) < parseFloat(product.price);

                  return (
                    <div
                      key={product.id}
                      onClick={() => handleResultClick(product.product_slug)}
                      className="group flex items-center justify-between p-2.5 rounded-xl bg-white/[0.02] border border-white/[0.04] hover:bg-white/[0.06] hover:border-white/[0.1] transition-all duration-300 cursor-pointer"
                    >
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-12 h-12 relative rounded-lg bg-zinc-900 overflow-hidden shrink-0 border border-white/5 flex items-center justify-center">
                          <Image
                            src={product.image_url || "/placeholder-product.svg"}
                            alt={product.name}
                            width={48}
                            height={48}
                            className="object-contain w-full h-full transition-transform duration-500 group-hover:scale-105"
                          />
                        </div>
                        <div className="min-w-0">
                          <p className="text-[10px] uppercase tracking-wider font-extrabold text-brand-accent group-hover:text-amber-400 transition-colors">
                            {product.product_name}
                          </p>
                          <p className="text-sm font-bold text-white truncate max-w-md">
                            {product.name}
                          </p>
                          <div className="flex items-center gap-2 mt-0.5">
                            <span className="text-[10px] text-zinc-500 font-mono uppercase tracking-wider">
                              SKU: {product.sku}
                            </span>
                            <span
                              className={`text-[9px] px-1.5 py-0.5 rounded-full font-black uppercase tracking-wider ${
                                product.in_stock
                                  ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/15"
                                  : "bg-red-500/10 text-red-400 border border-red-500/15"
                              }`}
                            >
                              {product.in_stock ? `In Stock (${product.stock_count})` : "Out of Stock"}
                            </span>
                          </div>
                        </div>
                      </div>

                      <div className="flex items-center gap-4 shrink-0">
                        <div className="text-right">
                          {hasDiscount ? (
                            <div className="flex flex-col items-end">
                              <span className="text-sm font-black text-brand-accent">
                                ৳{parseFloat(product.final_price).toFixed(0)}
                              </span>
                              <span className="text-[10px] text-zinc-500 line-through">
                                ৳{parseFloat(product.price).toFixed(0)}
                              </span>
                            </div>
                          ) : (
                            <span className="text-sm font-black text-white">
                              ৳{parseFloat(product.price).toFixed(0)}
                            </span>
                          )}
                        </div>
                        <div className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center text-zinc-500 group-hover:text-white group-hover:bg-brand-accent transition-all duration-300">
                          <CornerDownLeft className="w-3.5 h-3.5" />
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* Pagination & Keyboard Navigation Footer */}
        {results.length > 0 && pages > 1 && (
          <div className="border-t border-white/10 px-4 py-3 flex items-center justify-between bg-zinc-950/80">
            <div className="text-[10px] uppercase tracking-wider font-extrabold text-zinc-500">
              Page {page} of {pages}
            </div>
            <div className="flex items-center gap-1.5">
              <button
                disabled={page === 1}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                className="px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded border border-white/5 hover:border-white/10 bg-white/5 hover:bg-white/10 text-zinc-300 disabled:opacity-30 disabled:pointer-events-none transition cursor-pointer"
              >
                Prev
              </button>
              <button
                disabled={page === pages}
                onClick={() => setPage((p) => Math.min(pages, p + 1))}
                className="px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded border border-white/5 hover:border-white/10 bg-white/5 hover:bg-white/10 text-zinc-300 disabled:opacity-30 disabled:pointer-events-none transition cursor-pointer"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
