"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Search, MapPin, X } from "lucide-react";
import { useDebouncedCallback } from "use-debounce";

interface JobSearchHeroProps {
    totalJobs: number;
    recentSearches?: string[];
}

interface AutocompleteResults {
    titles: string[];
    companies: string[];
    locations: string[];
    recent: string[];
    popular: string[];
}

// ─── Trending chips matching Stitch design ──────────────────────────────────
const TRENDING_CHIPS = [
    "Frontend Developer",
    "Product Manager",
    "Data Scientist",
    "UI/UX Designer",
    "DevOps Engineer",
];

export function JobSearchHero({ totalJobs, recentSearches = [] }: JobSearchHeroProps) {
    const router = useRouter();
    const searchParams = useSearchParams();
    const inputRef = useRef<HTMLInputElement>(null);
    const dropdownRef = useRef<HTMLDivElement>(null);

    const [query, setQuery] = useState(searchParams.get("q") || "");
    const [location, setLocation] = useState(searchParams.get("l") || "");
    const [showDropdown, setShowDropdown] = useState(false);
    const [results, setResults] = useState<AutocompleteResults | null>(null);
    const [activeIndex, setActiveIndex] = useState(-1);
    const [isLoading, setIsLoading] = useState(false);

    // Flatten all suggestions for keyboard navigation
    const allSuggestions = results
        ? [
            ...results.recent.map((r) => ({ type: "recent", value: r })),
            ...results.titles.map((t) => ({ type: "title", value: t })),
            ...results.companies.map((c) => ({ type: "company", value: c })),
            ...results.locations.map((l) => ({ type: "location", value: l })),
            ...results.popular.map((p) => ({ type: "popular", value: p })),
        ]
        : recentSearches.map((r) => ({ type: "recent", value: r }));

    const handleSearch = useCallback(() => {
        const params = new URLSearchParams(searchParams.toString());
        if (query) params.set("q", query); else params.delete("q");
        if (location) params.set("l", location); else params.delete("l");
        params.delete("page");
        router.push(`/jobs?${params.toString()}`);
        setShowDropdown(false);
    }, [query, location, searchParams, router]);

    // Debounced autocomplete fetch
    const fetchAutocomplete = useDebouncedCallback(async (q: string) => {
        if (q.length < 2) {
            setResults(null);
            return;
        }
        setIsLoading(true);
        try {
            const res = await fetch(`/api/search/autocomplete?q=${encodeURIComponent(q)}`);
            if (res.ok) {
                const data = await res.json();
                setResults(data);
            }
        } catch (error) {
            console.error("Autocomplete fetch failed:", error);
        } finally {
            setIsLoading(false);
        }
    }, 300);

    const handleInputChange = (value: string) => {
        setQuery(value);
        setActiveIndex(-1);
        if (value.length >= 2) {
            fetchAutocomplete(value);
            setShowDropdown(true);
        } else if (value.length === 0) {
            setResults(null);
            setShowDropdown(recentSearches.length > 0);
        } else {
            setResults(null);
            setShowDropdown(false);
        }
    };

    const selectSuggestion = (suggestion: { type: string; value: string }) => {
        if (suggestion.type === "location") {
            setLocation(suggestion.value);
        } else {
            setQuery(suggestion.value);
        }
        setShowDropdown(false);
        setActiveIndex(-1);
        setTimeout(() => {
            const params = new URLSearchParams(searchParams.toString());
            if (suggestion.type === "location") {
                params.set("l", suggestion.value);
                if (query) params.set("q", query);
            } else {
                params.set("q", suggestion.value);
                if (location) params.set("l", location);
            }
            params.delete("page");
            router.push(`/jobs?${params.toString()}`);
        }, 0);
    };

    // Keyboard navigation
    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (!showDropdown || allSuggestions.length === 0) {
            if (e.key === "Enter") handleSearch();
            return;
        }

        switch (e.key) {
            case "ArrowDown":
                e.preventDefault();
                setActiveIndex((prev) => Math.min(prev + 1, allSuggestions.length - 1));
                break;
            case "ArrowUp":
                e.preventDefault();
                setActiveIndex((prev) => Math.max(prev - 1, -1));
                break;
            case "Enter":
                e.preventDefault();
                if (activeIndex >= 0 && activeIndex < allSuggestions.length) {
                    selectSuggestion(allSuggestions[activeIndex]);
                } else {
                    handleSearch();
                }
                break;
            case "Escape":
                setShowDropdown(false);
                setActiveIndex(-1);
                break;
        }
    };

    // Close on click outside
    useEffect(() => {
        const handleClick = (e: MouseEvent) => {
            if (
                dropdownRef.current &&
                !dropdownRef.current.contains(e.target as Node) &&
                inputRef.current &&
                !inputRef.current.contains(e.target as Node)
            ) {
                setShowDropdown(false);
            }
        };
        document.addEventListener("mousedown", handleClick);
        return () => document.removeEventListener("mousedown", handleClick);
    }, []);

    const handleTrendingChipClick = (term: string) => {
        setQuery(term);
        const params = new URLSearchParams(searchParams.toString());
        params.set("q", term);
        params.delete("page");
        router.push(`/jobs?${params.toString()}`);
    };

    // Group suggestions by type for display
    const ICON_MAP: Record<string, string> = {
        recent: "🕐",
        title: "💼",
        company: "🏢",
        location: "📍",
        popular: "🔥",
    };

    const LABEL_MAP: Record<string, string> = {
        recent: "Recent",
        title: "Jobs",
        company: "Companies",
        location: "Locations",
        popular: "Trending",
    };

    const groupedSuggestions: { type: string; items: { type: string; value: string; _index?: number }[] }[] = [];
    let globalIndex = 0;
    const types = ["recent", "title", "company", "location", "popular"];
    for (const type of types) {
        const items = allSuggestions.filter((s) => s.type === type);
        if (items.length > 0) {
            groupedSuggestions.push({ type, items: items.map((i) => ({ ...i, _index: globalIndex++ })) });
        }
    }

    return (
        <div className="relative bg-gradient-to-b from-slate-50 via-white to-slate-50/50 pt-24 pb-10 sm:pt-28 sm:pb-14 border-b border-slate-100">
            <div className="max-w-4xl mx-auto px-4 text-center">
                {/* Headline — Stitch "Find your next" style */}
                <h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold tracking-tight text-slate-900 mb-4 font-display">
                    Find your next
                </h1>
                <p className="text-base sm:text-lg text-slate-500 mb-8 max-w-2xl mx-auto">
                    Curated opportunities from Africa&apos;s most innovative companies and ambitious startups.
                </p>

                {/* Search Bar — clean white card style matching Stitch design */}
                <div className="mx-auto max-w-3xl relative">
                    <div className="flex flex-col sm:flex-row items-stretch gap-3 rounded-2xl bg-white p-2 shadow-lg shadow-slate-200/50 border border-slate-200">
                        {/* Job title input */}
                        <div className="relative flex flex-1 items-center gap-3 rounded-xl bg-slate-50 px-4 py-3">
                            <Search className="h-5 w-5 text-slate-400 shrink-0" />
                            <input
                                ref={inputRef}
                                type="text"
                                placeholder="Job title, keywords, or company"
                                className="w-full bg-transparent text-slate-800 outline-none placeholder:text-slate-400 text-sm font-medium"
                                value={query}
                                onChange={(e) => handleInputChange(e.target.value)}
                                onFocus={() => {
                                    if (query.length >= 2 || recentSearches.length > 0) setShowDropdown(true);
                                }}
                                onKeyDown={handleKeyDown}
                                autoComplete="off"
                                aria-label="Search jobs"
                                aria-expanded={showDropdown}
                                aria-controls="search-dropdown"
                                role="combobox"
                            />
                            {query && (
                                <button
                                    onClick={() => { setQuery(""); setResults(null); setShowDropdown(false); inputRef.current?.focus(); }}
                                    className="p-1 rounded-full hover:bg-slate-200 transition-colors"
                                    aria-label="Clear search"
                                >
                                    <X className="h-3.5 w-3.5 text-slate-400" />
                                </button>
                            )}
                            {isLoading && (
                                <div className="h-4 w-4 shrink-0 animate-spin rounded-full border-2 border-primary border-t-transparent" />
                            )}
                        </div>

                        {/* Location input */}
                        <div className="flex flex-1 items-center gap-3 rounded-xl bg-slate-50 px-4 py-3 sm:max-w-[220px]">
                            <MapPin className="h-5 w-5 text-slate-400 shrink-0" />
                            <input
                                type="text"
                                placeholder="City, state, or 'Remote'"
                                className="w-full bg-transparent text-slate-800 outline-none placeholder:text-slate-400 text-sm font-medium"
                                value={location}
                                onChange={(e) => setLocation(e.target.value)}
                                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                                aria-label="Search location"
                            />
                            {location && (
                                <button
                                    onClick={() => setLocation("")}
                                    className="p-1 rounded-full hover:bg-slate-200 transition-colors"
                                    aria-label="Clear location"
                                >
                                    <X className="h-3.5 w-3.5 text-slate-400" />
                                </button>
                            )}
                        </div>

                        {/* Search button */}
                        <button
                            onClick={handleSearch}
                            className="rounded-xl bg-primary px-8 py-3 font-bold text-white transition-all hover:bg-primary/90 hover:shadow-lg hover:shadow-primary/20 active:scale-[0.98] shrink-0"
                        >
                            Search
                        </button>
                    </div>

                    {/* Autocomplete Dropdown */}
                    {showDropdown && allSuggestions.length > 0 && (
                        <div
                            ref={dropdownRef}
                            id="search-dropdown"
                            className="absolute left-2 right-2 sm:left-2 sm:right-auto sm:w-[calc(100%-240px)] top-full mt-1 z-50 rounded-xl bg-white shadow-2xl border border-slate-200 overflow-hidden"
                            role="listbox"
                        >
                            <div className="max-h-[320px] overflow-y-auto py-2">
                                {groupedSuggestions.map((group) => (
                                    <div key={group.type}>
                                        <p className="px-4 py-1.5 text-[10px] font-bold uppercase tracking-wider text-slate-400">
                                            {LABEL_MAP[group.type]}
                                        </p>
                                        {group.items.map((item) => {
                                            const idx = item._index ?? 0;
                                            return (
                                                <button
                                                    key={`${item.type}-${item.value}`}
                                                    onClick={() => selectSuggestion(item)}
                                                    className={`flex w-full items-center gap-3 px-4 py-2 text-sm text-left transition-colors ${idx === activeIndex
                                                        ? "bg-primary/5 text-primary"
                                                        : "text-slate-700 hover:bg-slate-50"
                                                        }`}
                                                    role="option"
                                                    aria-selected={idx === activeIndex}
                                                >
                                                    <span className="text-sm">{ICON_MAP[item.type]}</span>
                                                    <span className="truncate">{item.value}</span>
                                                </button>
                                            );
                                        })}
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>

                {/* Trending chips — matching Stitch "Trending:" row */}
                <div className="mt-6 flex flex-wrap items-center justify-center gap-2">
                    <span className="text-sm text-slate-400 mr-1">Trending:</span>
                    {TRENDING_CHIPS.map((term) => (
                        <button
                            key={term}
                            onClick={() => handleTrendingChipClick(term)}
                            className={`rounded-full px-4 py-1.5 text-sm font-medium transition-all border ${
                                query === term
                                    ? "bg-primary text-white border-primary shadow-sm"
                                    : "bg-white text-slate-600 border-slate-200 hover:border-primary hover:text-primary"
                            }`}
                        >
                            {term}
                        </button>
                    ))}
                </div>
            </div>
        </div>
    );
}
