import { Link } from '@inertiajs/react';
import { LoaderCircle, MapPin, PackageSearch, Search, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Input } from '@/components/ui/input';
import type { Product } from '@/pages/frontend/types';

type SearchResponse = {
    products: Product[];
};

export default function FrontendProductSearch() {
    const [query, setQuery] = useState('');
    const [products, setProducts] = useState<Product[]>([]);
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const requestId = useRef(0);

    useEffect(() => {
        const search = query.trim();

        if (search.length < 2) {
            return;
        }

        const currentRequest = ++requestId.current;

        const timeout = window.setTimeout(async () => {
            try {
                const response = await fetch(
                    `/product-search?q=${encodeURIComponent(search)}`,
                    { headers: { Accept: 'application/json' } },
                );
                const data = (await response.json()) as SearchResponse;

                if (currentRequest === requestId.current) {
                    setProducts(data.products);
                }
            } catch {
                if (currentRequest === requestId.current) {
                    setProducts([]);
                }
            } finally {
                if (currentRequest === requestId.current) {
                    setLoading(false);
                }
            }
        }, 250);

        return () => window.clearTimeout(timeout);
    }, [query]);

    return (
        <div className="relative w-full">
            <Search className="pointer-events-none absolute top-1/2 left-4 z-10 size-4 -translate-y-1/2 text-slate-400" />
            <Input
                value={query}
                onChange={(event) => {
                    const value = event.target.value;
                    setQuery(value);
                    setOpen(true);

                    if (value.trim().length < 2) {
                        requestId.current++;
                        setProducts([]);
                        setLoading(false);
                    } else {
                        setLoading(true);
                    }
                }}
                onFocus={() => setOpen(true)}
                placeholder="Search products, brands, or categories..."
                className="h-11 rounded-full border-slate-200 bg-slate-50 pr-10 pl-11 shadow-none focus-visible:bg-white dark:border-slate-700 dark:bg-slate-900"
            />
            {query && (
                <button
                    type="button"
                    onClick={() => {
                        setQuery('');
                        setProducts([]);
                    }}
                    className="absolute top-1/2 right-4 z-10 -translate-y-1/2 text-slate-400 hover:text-slate-900 dark:hover:text-white"
                    aria-label="Clear search"
                >
                    <X className="size-4" />
                </button>
            )}

            {open && query.trim().length >= 2 && (
                <>
                    <button
                        type="button"
                        className="fixed inset-0 z-40 cursor-default"
                        onClick={() => setOpen(false)}
                        aria-label="Close search results"
                    />
                    <div className="absolute top-full right-0 left-0 z-50 mt-3 overflow-hidden rounded-2xl border bg-background shadow-2xl shadow-slate-950/15">
                        <div className="flex items-center justify-between border-b px-4 py-3">
                            <div className="text-sm font-semibold">
                                Product availability
                            </div>
                            <div className="text-xs text-muted-foreground">
                                {loading
                                    ? 'Searching...'
                                    : `${products.length} result${products.length === 1 ? '' : 's'}`}
                            </div>
                        </div>

                        <div className="max-h-[min(65vh,520px)] overflow-y-auto p-2">
                            {loading && (
                                <div className="flex items-center justify-center gap-2 px-4 py-10 text-sm text-muted-foreground">
                                    <LoaderCircle className="size-4 animate-spin" />
                                    Searching catalog
                                </div>
                            )}

                            {!loading &&
                                products.map((product) => (
                                    <Link
                                        key={product.id}
                                        href={`/product/${product.slug}`}
                                        onClick={() => setOpen(false)}
                                        className="flex items-center gap-3 rounded-xl p-3 transition-colors hover:bg-muted"
                                    >
                                        <div className="flex size-14 shrink-0 items-center justify-center overflow-hidden rounded-xl border bg-muted">
                                            {product.feature_image_url ? (
                                                <img
                                                    src={
                                                        product.feature_image_url
                                                    }
                                                    alt={product.name}
                                                    className="size-full object-cover"
                                                />
                                            ) : (
                                                <PackageSearch className="size-5 text-muted-foreground" />
                                            )}
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <div className="truncate text-sm font-semibold">
                                                {product.name}
                                            </div>
                                            <div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
                                                <MapPin className="size-3" />
                                                {product.store?.name ??
                                                    'Store unavailable'}
                                            </div>
                                        </div>
                                        <div className="shrink-0 text-right">
                                            <div
                                                className={`text-sm font-semibold ${
                                                    product.stock > 0
                                                        ? 'text-emerald-600 dark:text-emerald-400'
                                                        : 'text-rose-600 dark:text-rose-400'
                                                }`}
                                            >
                                                {product.stock} available
                                            </div>
                                            <div className="mt-1 text-xs text-muted-foreground">
                                                {product.price}
                                            </div>
                                        </div>
                                    </Link>
                                ))}

                            {!loading && products.length === 0 && (
                                <div className="px-4 py-10 text-center">
                                    <PackageSearch className="mx-auto size-8 text-muted-foreground" />
                                    <div className="mt-3 text-sm font-medium">
                                        No products found
                                    </div>
                                    <p className="mt-1 text-xs text-muted-foreground">
                                        Try another product, brand, or category.
                                    </p>
                                </div>
                            )}
                        </div>

                        {!loading && products.length > 0 && (
                            <Link
                                href={`/shop?search=${encodeURIComponent(query.trim())}`}
                                onClick={() => setOpen(false)}
                                className="block border-t bg-muted/30 px-4 py-3 text-center text-sm font-medium hover:bg-muted"
                            >
                                View all matching products
                            </Link>
                        )}
                    </div>
                </>
            )}
        </div>
    );
}
