"use client";

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Search, X, Loader2 } from 'lucide-react';
import Image from 'next/image';

interface SearchResult {
    id: number;
    name: string;
    price: number;
    brand: string;
    image?: string;
}

interface NavbarSearchProps {
    variant?: 'desktop' | 'mobile';
}

export default function NavbarSearch({ variant = 'desktop' }: NavbarSearchProps) {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState<SearchResult[]>([]);
    const [isOpen, setIsOpen] = useState(false);
    const [isExpanded, setIsExpanded] = useState(false);
    const [loading, setLoading] = useState(false);
    const searchRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);
    const router = useRouter();

    // Debounce Search
    useEffect(() => {
        const timeoutId = setTimeout(async () => {
            if (query.trim().length >= 2) {
                setLoading(true);
                try {
                    const res = await fetch(`/api/products/search?q=${encodeURIComponent(query)}`);
                    if (res.ok) {
                        const data = await res.json();
                        setResults(data);
                        setIsOpen(true);
                    }
                } catch (err) {
                    console.error('Search error', err);
                } finally {
                    setLoading(false);
                }
            } else {
                setResults([]);
                setIsOpen(false);
            }
        }, 300);

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

    // Close on click outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
                setIsOpen(false);
                if (variant === 'mobile' && !query) {
                    setIsExpanded(false);
                }
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [variant, query]);

    useEffect(() => {
        if (isExpanded && inputRef.current) {
            inputRef.current.focus();
        }
    }, [isExpanded]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (query.trim()) {
            setIsOpen(false);
            setIsExpanded(false);
            router.push(`/products?q=${encodeURIComponent(query)}`);
        }
    };

    const handleMobileIconClick = () => {
        setIsExpanded(true);
    };

    const closeSearch = () => {
        setQuery('');
        setResults([]);
        setIsOpen(false);
        setIsExpanded(false);
    };

    return (
        <>
            <div className="relative" ref={searchRef}>
                {variant === 'mobile' ? (
                    <button
                        onClick={handleMobileIconClick}
                        className="p-2 text-[var(--nav-text)] hover:text-[var(--nav-hover)] transition-colors"
                    >
                        <Search size={24} />
                    </button>
                ) : variant === 'desktop' ? (
                    <>
                        <form onSubmit={handleSubmit} className="relative">
                            <input
                                ref={inputRef}
                                type="text"
                                placeholder="Sök..."
                                className="pl-9 pr-4 py-2 bg-[var(--background)] text-[var(--foreground)] rounded-lg text-sm border border-[var(--border-color)] focus:ring-2 focus:ring-[var(--primary-color)] w-[180px] focus:w-[280px] transition-all duration-300 placeholder-gray-500"
                                value={query}
                                onChange={(e) => setQuery(e.target.value)}
                                onFocus={() => { if (results.length > 0) setIsOpen(true); }}
                            />
                            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
                            {query && (
                                <button
                                    type="button"
                                    onClick={closeSearch}
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                >
                                    <X size={14} />
                                </button>
                            )}
                        </form>

                        {/* Desktop Dropdown Results */}
                        {isOpen && (
                            <div className="absolute top-full right-0 mt-2 w-80 bg-[var(--card-bg)] rounded-xl shadow-2xl border border-[var(--border-color)] overflow-hidden z-50">
                                <div className="p-2">
                                    {loading ? (
                                        <div className="p-4 text-center text-gray-500 flex items-center justify-center gap-2">
                                            <Loader2 size={16} className="animate-spin" /> Söker...
                                        </div>
                                    ) : results.length > 0 ? (
                                        <>
                                            <h3 className="text-xs font-bold text-gray-500 uppercase px-2 mb-2">Förslag</h3>
                                            <ul className="space-y-1">
                                                {results.map(result => (
                                                    <li key={result.id}>
                                                        <Link
                                                            href={`/products/${result.id}`}
                                                            className="flex items-center gap-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg group"
                                                            onClick={() => { setIsOpen(false); }}
                                                        >
                                                            <div className="w-10 h-10 bg-gray-200 rounded-md overflow-hidden relative flex-shrink-0">
                                                                {result.image ? (
                                                                    <Image
                                                                        src={result.image}
                                                                        alt={result.name}
                                                                        className="object-cover"
                                                                        fill
                                                                        sizes="40px"
                                                                        unoptimized={result.image.startsWith('http')}
                                                                    />
                                                                ) : (
                                                                    <div className="flex items-center justify-center h-full text-gray-400">?</div>
                                                                )}
                                                            </div>
                                                            <div className="flex-grow min-w-0">
                                                                <div className="font-medium text-sm truncate group-hover:text-[var(--primary-color)] transition-colors">
                                                                    {result.name}
                                                                </div>
                                                                <div className="text-xs text-gray-500">
                                                                    {result.brand} · {result.price.toLocaleString()} kr
                                                                </div>
                                                            </div>
                                                        </Link>
                                                    </li>
                                                ))}
                                            </ul>
                                            <div className="border-t border-[var(--border-color)] mt-2 pt-2 text-center">
                                                <button
                                                    onClick={() => { setIsOpen(false); router.push(`/products?q=${encodeURIComponent(query)}`); }}
                                                    className="text-sm text-[var(--primary-color)] font-bold hover:underline"
                                                >
                                                    Visa alla resultat ({results.length}+)
                                                </button>
                                            </div>
                                        </>
                                    ) : (
                                        <div className="p-4 text-center text-gray-500">
                                            Inga produkter hittades.
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}
                    </>
                ) : null}
            </div>

            {/* Mobile Expanded Search - Fixed Overlay */}
            {variant === 'mobile' && isExpanded && (
                <div className="fixed left-0 right-0 bg-[var(--primary-color)] shadow-lg z-[150] p-4 border-b border-[var(--border-color)]" style={{ top: '90px' }}>
                    <form onSubmit={handleSubmit} className="relative max-w-2xl mx-auto">
                        <input
                            ref={inputRef}
                            type="text"
                            placeholder="Sök..."
                            className="w-full pl-10 pr-12 py-3 bg-[var(--background)] text-[var(--foreground)] rounded-lg text-base border border-[var(--border-color)] focus:ring-2 focus:ring-[var(--primary-color)] transition-all duration-300 placeholder-gray-500"
                            value={query}
                            onChange={(e) => setQuery(e.target.value)}
                            onFocus={() => { if (results.length > 0) setIsOpen(true); }}
                        />
                        <Search size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500" />
                        <button
                            type="button"
                            onClick={closeSearch}
                            className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        >
                            <X size={20} />
                        </button>
                    </form>

                    {/* Mobile Search Results */}
                    {isOpen && (
                        <div className="mt-4 max-w-2xl mx-auto bg-[var(--card-bg)] rounded-xl shadow-2xl border border-[var(--border-color)] overflow-hidden max-h-[60vh] overflow-y-auto">
                            <div className="p-2">
                                {loading ? (
                                    <div className="p-4 text-center text-gray-500 flex items-center justify-center gap-2">
                                        <Loader2 size={16} className="animate-spin" /> Söker...
                                    </div>
                                ) : results.length > 0 ? (
                                    <>
                                        <h3 className="text-xs font-bold text-gray-500 uppercase px-2 mb-2">Förslag</h3>
                                        <ul className="space-y-1">
                                            {results.map(result => (
                                                <li key={result.id}>
                                                    <Link
                                                        href={`/products/${result.id}`}
                                                        className="flex items-center gap-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg group"
                                                        onClick={closeSearch}
                                                    >
                                                        <div className="w-10 h-10 bg-gray-200 rounded-md overflow-hidden relative flex-shrink-0">
                                                            {result.image ? (
                                                                <Image
                                                                    src={result.image}
                                                                    alt={result.name}
                                                                    className="object-cover"
                                                                    fill
                                                                    sizes="40px"
                                                                    unoptimized={result.image.startsWith('http')}
                                                                />
                                                            ) : (
                                                                <div className="flex items-center justify-center h-full text-gray-400">?</div>
                                                            )}
                                                        </div>
                                                        <div className="flex-grow min-w-0">
                                                            <div className="font-medium text-sm truncate group-hover:text-[var(--primary-color)] transition-colors">
                                                                {result.name}
                                                            </div>
                                                            <div className="text-xs text-gray-500">
                                                                {result.brand} · {result.price.toLocaleString()} kr
                                                            </div>
                                                        </div>
                                                    </Link>
                                                </li>
                                            ))}
                                        </ul>
                                        <div className="border-t border-[var(--border-color)] mt-2 pt-2 text-center">
                                            <button
                                                onClick={() => { closeSearch(); router.push(`/products?q=${encodeURIComponent(query)}`); }}
                                                className="text-sm text-[var(--primary-color)] font-bold hover:underline"
                                            >
                                                Visa alla resultat ({results.length}+)
                                            </button>
                                        </div>
                                    </>
                                ) : (
                                    <div className="p-4 text-center text-gray-500">
                                        Inga produkter hittades.
                                    </div>
                                )}
                            </div>
                        </div>
                    )}
                </div>
            )}
        </>
    );
}
