"use client";

import React, { useState, useRef, useEffect } from "react";
import { Search, ChevronDown, MapPin, Layers, Type, Check } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

interface UnifiedSearchBarProps {
    searchQuery: string;
    setSearchQuery: (val: string) => void;
    selectedState: string;
    setSelectedState: (val: string) => void;
    states: string[];
    selectedDistrict: string;
    setSelectedDistrict: (val: string) => void;
    districts: string[];
    selectedCategory: string;
    setSelectedCategory: (val: string) => void;
    categories: string[];
    onSearch: () => void;
    onAdvanceToggle?: () => void;
}

const SearchableDropdown = ({
    value,
    options,
    onChange,
    icon: Icon,
    placeholder = "Select Option",
    className = ""
}: {
    value: string,
    options: string[],
    onChange: (val: string) => void,
    icon: any,
    placeholder?: string,
    className?: string
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState("");
    const dropdownRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
                setSearchTerm("");
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    const filteredOptions = options.filter(opt =>
        opt.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className={`relative ${className}`} ref={dropdownRef}>
            <div className="w-full flex items-center gap-2 px-3 py-3 group hover:bg-blue-50/50 transition-all duration-200">
                <div className="text-blue-500 group-focus-within:scale-110 transition-transform duration-200">
                    <Icon className="w-5 h-5" />
                </div>
                <div className="flex flex-col min-w-0 flex-1 justify-center">
                    <input
                        type="text"
                        value={isOpen ? searchTerm : (value || "")}
                        onChange={(e) => {
                            setSearchTerm(e.target.value);
                            if (!isOpen) setIsOpen(true);
                        }}
                        onFocus={() => {
                            setIsOpen(true);
                            setSearchTerm("");
                        }}
                        placeholder={placeholder}
                        className="w-full bg-transparent border-none focus:ring-0 text-gray-700 font-semibold p-0 placeholder-gray-400 text-sm outline-none"
                    />
                </div>
                <button
                    type="button"
                    onClick={() => {
                        setIsOpen(!isOpen);
                        if (!isOpen) setSearchTerm("");
                    }}
                    className="p-1"
                >
                    <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform duration-300 ${isOpen ? 'rotate-180 text-blue-500' : ''}`} />
                </button>
            </div>

            <AnimatePresence>
                {isOpen && (
                    <motion.div
                        initial={{ opacity: 0, y: 5, scale: 0.98 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        exit={{ opacity: 0, y: 5, scale: 0.98 }}
                        transition={{ duration: 0.15 }}
                        className="absolute z-[100] top-full left-0 right-0 mt-1 bg-white rounded-lg shadow-2xl border border-gray-100 overflow-hidden max-h-[250px] flex flex-col"
                    >
                        <div className="flex-1 overflow-y-auto py-1 custom-scrollbar">
                            {filteredOptions.length > 0 ? (
                                filteredOptions.map((opt) => (
                                    <button
                                        key={opt}
                                        type="button"
                                        onClick={() => {
                                            onChange(opt);
                                            setIsOpen(false);
                                            setSearchTerm("");
                                        }}
                                        className={`w-full flex items-center justify-between px-4 py-2 text-sm transition-colors ${value === opt
                                            ? "bg-blue-50 text-blue-700 font-bold"
                                            : "text-gray-600 hover:bg-gray-50"
                                            }`}
                                    >
                                        <span className="truncate">{opt}</span>
                                        {value === opt && <Check className="w-4 h-4 text-blue-600" />}
                                    </button>
                                ))
                            ) : (
                                <div className="px-4 py-4 text-center">
                                    <p className="text-gray-400 text-xs">No results found</p>
                                </div>
                            )}
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
};

export default function UnifiedSearchBar({
    searchQuery,
    setSearchQuery,
    selectedState,
    setSelectedState,
    states,
    selectedDistrict,
    setSelectedDistrict,
    districts,
    selectedCategory,
    setSelectedCategory,
    categories,
    onSearch,
    onAdvanceToggle,
}: UnifiedSearchBarProps) {
    return (
        <div className="w-full max-w-6xl mx-auto space-y-4">
            <div className="flex flex-col lg:flex-row items-stretch bg-white rounded-xl border border-gray-200 shadow-lg overflow-visible lg:h-[56px]">

                {/* City (State) Search */}
                <SearchableDropdown
                    value={selectedState}
                    options={Array.from(new Set(["All India", ...states]))}
                    onChange={(val) => setSelectedState(val === "All India" ? "" : val)}
                    icon={MapPin}
                    placeholder="All India (City)"
                    className="flex-[2] min-w-[170px] border-b lg:border-b-0 lg:border-r border-gray-100"
                />

                {/* District Search */}
                <SearchableDropdown
                    value={selectedDistrict}
                    options={Array.from(new Set(districts))}
                    onChange={setSelectedDistrict}
                    icon={MapPin}
                    placeholder="All Districts"
                    className="flex-[2] min-w-[170px] border-b lg:border-b-0 lg:border-r border-gray-100"
                />

                {/* Category Search */}
                <SearchableDropdown
                    value={selectedCategory}
                    options={Array.from(new Set(categories))}
                    onChange={setSelectedCategory}
                    icon={Layers}
                    placeholder="All Categories"
                    className="flex-[2.5] min-w-[190px] border-b lg:border-b-0 lg:border-r border-gray-100"
                />

                {/* Search Input */}
                <div className="flex-[3] relative border-b lg:border-b-0 lg:border-r border-gray-100 group">
                    <div className="absolute left-3 top-1/2 -translate-y-1/2 text-blue-500 group-focus-within:scale-110 transition-transform duration-200">
                        <Type className="w-5 h-5" />
                    </div>
                    <div className="flex flex-col pl-10 pr-4 py-3 h-full justify-center">
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="Search Keywords..."
                            className="bg-transparent border-none focus:ring-0 text-gray-700 font-semibold p-0 placeholder-gray-400 text-sm outline-none w-full"
                            onKeyDown={(e) => e.key === "Enter" && onSearch()}
                        />
                    </div>
                </div>

                {/* Search Button */}
                <div className="p-2 lg:p-0 flex items-stretch">
                    <button
                        onClick={onSearch}
                        className="w-full lg:px-6 py-3 lg:py-0 bg-gradient-to-r from-blue-600 to-indigo-700 hover:from-blue-700 hover:to-indigo-800 text-white font-black flex items-center justify-center gap-2 transition-all active:scale-95 lg:rounded-r-xl shadow-lg shadow-blue-500/20"
                    >
                        <Search className="w-5 h-5 stroke-[3px]" />
                        <span className="tracking-widest uppercase text-sm">AI SEARCH</span>
                    </button>
                </div>
            </div>

            {/* Advance Search Button Downside */}
            <div className="flex justify-center pt-2">
                {onAdvanceToggle && (
                    <button
                        onClick={onAdvanceToggle}
                        className="flex items-center gap-3 px-8 py-2.5 bg-gradient-to-r from-rose-600 to-red-600 hover:from-rose-700 hover:to-red-700 text-white font-black text-[10px] tracking-[0.2em] rounded-full shadow-lg shadow-red-500/30 transition-all active:scale-95 uppercase group"
                    >
                        <Layers className="w-4 h-4 animate-pulse group-hover:animate-none" />
                        ADVANCED FILTERS & SEARCH
                    </button>
                )}
            </div>

            <style jsx global>{`
                .custom-scrollbar::-webkit-scrollbar {
                    width: 6px;
                }
                .custom-scrollbar::-webkit-scrollbar-track {
                    background: transparent;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb {
                    background: #e2e8f0;
                    border-radius: 10px;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb:hover {
                    background: #cbd5e1;
                }
            `}</style>
        </div>
    );
}
