import React, { useState, useEffect, useRef } from 'react';
import { Link, router, usePage } from '@inertiajs/react';
import axios from 'axios';
import { Search, Loader2, PackageOpen, ArrowRight } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import { useTranslation } from '@/hooks/useTranslation'; 

export default function LiveSearch({ 
    placeholder = "Search products, categories...", 
    buttonText = "Search", 
    containerClassName = "", 
    inputClassName = "", 
    buttonClassName = "",
    showButton = true 
}) {
    const { t } = useTranslation(); 
    const { activeCurrency, currencies } = usePage().props; // <-- Fetch Global Currency Props
    
    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [isOpen, setIsOpen] = useState(false);
    
    const wrapperRef = useRef(null);

    // Handle Clicks Outside to close the dropdown
    useEffect(() => {
        function handleClickOutside(event) {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        }
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    // Debounced Search API Call
    useEffect(() => {
        if (query.trim().length < 2) {
            setResults([]);
            setIsOpen(false);
            return;
        }

        const delayDebounceFn = setTimeout(async () => {
            setIsLoading(true);
            try {
                const res = await axios.get(route('search.suggestions'), { params: { q: query } });
                setResults(res.data);
                setIsOpen(true);
            } catch (error) {
                console.error("Search failed", error);
            } finally {
                setIsLoading(false);
            }
        }, 300);

        return () => clearTimeout(delayDebounceFn);
    }, [query]);

    const handleFullSearch = (e) => {
        e?.preventDefault();
        if (query.trim()) {
            setIsOpen(false);
            router.get(route('search.index'), { q: query }); 
        }
    };

    return (
        <div ref={wrapperRef} className={`relative flex-1 ${containerClassName}`}>
            <form onSubmit={handleFullSearch} className="relative flex w-full h-full items-center">
                {!showButton && (
                    <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground z-10" />
                )}
                
                <input 
                    type="text"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    onFocus={() => { if (results.length > 0) setIsOpen(true) }}
                    placeholder={placeholder} 
                    className={`w-full focus:outline-none transition-all ${inputClassName}`}
                    autoComplete="off"
                />

                {isLoading && (
                    <div className={`absolute right-4 top-1/2 -translate-y-1/2 ${showButton ? 'right-28' : 'right-4'}`}>
                        <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
                    </div>
                )}

                {showButton && (
                    <Button 
                        type="submit"
                        className={`absolute right-0 top-0 bottom-0 h-full ${buttonClassName}`}
                    >
                        {buttonText} 
                    </Button>
                )}
            </form>

            {/* DROPDOWN RESULTS */}
            {isOpen && (
                <div className="absolute top-full left-0 w-full mt-2 bg-card border border-border shadow-xl rounded-xl z-50 overflow-hidden animate-in fade-in slide-in-from-top-2">
                    {results.length > 0 ? (
                        <div className="flex flex-col">
                            <div className="px-4 py-2 bg-muted/30 border-b text-xs font-bold text-muted-foreground uppercase tracking-wider">
                                {t('Products')} 
                            </div>
                            
                            {results.map((product) => {
                                const mainImg = product.images?.find(img => img.is_main)?.path || product.images?.[0]?.path;
                                
                                // --- DYNAMIC CURRENCY CONVERSION LOGIC ---
                                const productRate = currencies?.find(c => c.code === (product.currency_code || 'USD'))?.exchange_rate || 1;
                                const baseUsdPrice = parseFloat(product.original_price || product.price || 0) / parseFloat(productRate);
                                const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;
                                const finalDisplayPrice = baseUsdPrice * targetRate;
                                const currencySymbol = activeCurrency?.symbol || '$';
                                
                                return (
                                    <Link 
                                        key={product.id}
                                        href={route('product.view', `${product.slug}_${product.id}`)}
                                        onClick={() => setIsOpen(false)}
                                        className="flex items-center gap-4 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 group"
                                    >
                                        <div className="w-12 h-12 rounded-md bg-white border flex items-center justify-center overflow-hidden shrink-0">
                                            {mainImg ? (
                                                <img src={`/storage/${mainImg}`} alt={product.title} className="w-full h-full object-contain" />
                                            ) : (
                                                <div className="w-full h-full bg-muted flex items-center justify-center">
                                                    <PackageOpen className="w-5 h-5 text-muted-foreground opacity-30" />
                                                </div>
                                            )}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <p className="font-semibold text-sm truncate group-hover:text-primary transition-colors">
                                                {product.title}
                                            </p>
                                            <p className="text-xs text-muted-foreground truncate">
                                                {product.seller?.company_name || product.seller?.name}
                                            </p>
                                        </div>
                                        <div className="text-right shrink-0">
                                            <p className="font-black text-orange-600">
                                                {currencySymbol}{finalDisplayPrice.toFixed(2)}
                                            </p>
                                        </div>
                                    </Link>
                                );
                            })}
                            
                            <button 
                                onClick={handleFullSearch}
                                className="w-full p-3 bg-muted/20 hover:bg-muted/50 text-center text-sm font-bold text-primary flex items-center justify-center gap-2 transition-colors border-t"
                            >
                                {t('View all results for ":query"', { query: query })} 
                                <ArrowRight className="w-4 h-4" />
                            </button>
                        </div>
                    ) : (
                        <div className="p-6 text-center text-muted-foreground">
                            <p className="text-sm font-medium">{t('No exact matches found for ":query"', { query: query })}</p>
                            <p className="text-xs mt-1">{t('Try checking your spelling or using more general terms.')}</p>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}