"use client";

import { useState, useRef, useEffect } from "react";
import {
    locationOptions,
    propertyStatusOptions,
    propertyTypeOptions,
    unitSizeOptions,
} from "@/sections/properties/contents/filter/constants";
import { SearchFiltersState } from "@/app/property-search/page";
import gsap from "gsap";

interface SelectOption {
    value: string;
    label: string;
}

interface ModernDropdownProps {
    label: string;
    name: string;
    value: string;
    onChange: (name: string, value: string) => void;
    options: SelectOption[];
    icon: React.ReactNode;
}

const ModernDropdown = ({
    label,
    name,
    value,
    onChange,
    options,
    icon,
}: ModernDropdownProps) => {
    const [isOpen, setIsOpen] = useState(false);
    const selectedOption = options.find((opt) => opt.value === value);
    const dropdownRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    return (
        <div ref={dropdownRef} className="relative">
            <button
                type="button"
                onClick={() => setIsOpen(!isOpen)}
                className={`w-full flex items-center gap-3 text-left px-4 py-3.5 bg-white border rounded-xl transition-all duration-300 ${isOpen
                        ? "border-[#cd607f] ring-2 ring-[#cd607f]/10"
                        : "border-gray-200 hover:border-[#cd607f]/50"
                    }`}
            >
                <span className={`flex-shrink-0 transition-colors duration-300 ${isOpen ? "text-[#cd607f]" : "text-gray-400"}`}>
                    {icon}
                </span>
                <div className="flex-1 min-w-0">
                    <span className="block text-[10px] uppercase tracking-[0.15em] text-gray-400 font-creato font-medium mb-0.5">
                        {label}
                    </span>
                    <span className="block text-[14px] text-[#1a1a1a] font-creato font-normal truncate">
                        {selectedOption?.label || "Select..."}
                    </span>
                </div>
                <svg
                    className={`w-4 h-4 text-gray-400 transition-transform duration-300 ${isOpen ? "rotate-180 text-[#cd607f]" : ""}`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                </svg>
            </button>

            {/* Dropdown Menu */}
            {isOpen && (
                <div className="absolute top-full left-0 right-0 mt-2 bg-white border border-gray-100 rounded-xl shadow-xl shadow-black/5 z-50 overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
                    <div className="max-h-[280px] overflow-y-auto">
                        {options.map((option) => (
                            <button
                                key={option.value}
                                type="button"
                                onClick={() => {
                                    onChange(name, option.value);
                                    setIsOpen(false);
                                }}
                                className={`w-full text-left px-4 py-3 text-[14px] font-creato transition-all duration-200 ${option.value === value
                                        ? "bg-[#cd607f]/10 text-[#cd607f] font-medium"
                                        : "text-[#333] hover:bg-gray-50 hover:text-[#cd607f]"
                                    }`}
                            >
                                {option.label}
                            </button>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

// Icons for dropdowns
const BuildingIcon = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
        <path d="M3 21h18M5 21V7l8-4v18M19 21V11l-6-3M9 9v.01M9 12v.01M9 15v.01M9 18v.01" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
);

const LocationIcon = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
        <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx="12" cy="9" r="2.5" />
    </svg>
);

const SizeIcon = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
        <rect x="3" y="3" width="18" height="18" rx="2" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M3 9h18M9 21V9" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
);

const StatusIcon = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
        <circle cx="12" cy="12" r="10" />
        <path d="M12 6v6l4 2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
);

interface LuxurySearchFiltersProps {
    filters: SearchFiltersState;
    onFilterChange: (filters: SearchFiltersState) => void;
}

const LuxurySearchFilters = ({ filters, onFilterChange }: LuxurySearchFiltersProps) => {
    const containerRef = useRef<HTMLElement>(null);

    const handleChange = (name: string, value: string) => {
        onFilterChange({ ...filters, [name]: value });
    };

    const handleSearchQueryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        onFilterChange({ ...filters, searchQuery: e.target.value });
    };

    const handleReset = () => {
        onFilterChange({
            propertyType: "all",
            location: "all",
            size: "all",
            status: "all",
            searchQuery: "",
        });
    };

    const hasActiveFilters =
        filters.propertyType !== "all" ||
        filters.location !== "all" ||
        filters.size !== "all" ||
        filters.status !== "all" ||
        filters.searchQuery !== "";

    const activeFilterCount = [
        filters.propertyType !== "all",
        filters.location !== "all",
        filters.size !== "all",
        filters.status !== "all",
        filters.searchQuery !== "",
    ].filter(Boolean).length;

    useEffect(() => {
        const ctx = gsap.context(() => {
            gsap.fromTo(
                ".filter-item",
                { opacity: 0, y: 20 },
                { opacity: 1, y: 0, duration: 0.5, stagger: 0.1, ease: "power2.out" }
            );
        }, containerRef);

        return () => ctx.revert();
    }, []);

    return (
        <section ref={containerRef} className="sticky top-[80px] z-40 bg-[#F5F5F5] border-b border-gray-200/50">
            <div className="max-w-7xl mx-auto px-6 lg:px-8 py-6">
                {/* Search Bar */}
                <div className="filter-item mb-6">
                    <div className="relative">
                        <div className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <circle cx="11" cy="11" r="7" />
                                <path d="M21 21l-4.35-4.35" strokeLinecap="round" />
                            </svg>
                        </div>
                        <input
                            type="text"
                            value={filters.searchQuery}
                            onChange={handleSearchQueryChange}
                            placeholder="Search by project name, location, or keyword..."
                            className="w-full bg-white text-[#1a1a1a] text-[15px] font-creato font-light pl-12 pr-4 py-4 border border-gray-200 rounded-xl placeholder-gray-400 focus:outline-none focus:border-[#cd607f] focus:ring-2 focus:ring-[#cd607f]/10 transition-all duration-300"
                        />
                        {filters.searchQuery && (
                            <button
                                onClick={() => onFilterChange({ ...filters, searchQuery: "" })}
                                className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-[#cd607f] transition-colors"
                            >
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path d="M18 6L6 18M6 6l12 12" strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                            </button>
                        )}
                    </div>
                </div>

                {/* Filter Grid */}
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="filter-item">
                        <ModernDropdown
                            label="Property Type"
                            name="propertyType"
                            value={filters.propertyType}
                            onChange={handleChange}
                            options={propertyTypeOptions}
                            icon={<BuildingIcon />}
                        />
                    </div>
                    <div className="filter-item">
                        <ModernDropdown
                            label="Location"
                            name="location"
                            value={filters.location}
                            onChange={handleChange}
                            options={locationOptions}
                            icon={<LocationIcon />}
                        />
                    </div>
                    <div className="filter-item">
                        <ModernDropdown
                            label="Unit Size"
                            name="size"
                            value={filters.size}
                            onChange={handleChange}
                            options={unitSizeOptions}
                            icon={<SizeIcon />}
                        />
                    </div>
                    <div className="filter-item">
                        <ModernDropdown
                            label="Status"
                            name="status"
                            value={filters.status}
                            onChange={handleChange}
                            options={propertyStatusOptions}
                            icon={<StatusIcon />}
                        />
                    </div>
                </div>

                {/* Active Filters Bar */}
                {hasActiveFilters && (
                    <div className="filter-item flex items-center justify-between gap-4 mt-5 pt-5 border-t border-gray-200/50">
                        <div className="flex items-center gap-2">
                            <span className="inline-flex items-center justify-center w-6 h-6 bg-[#cd607f] text-white text-[11px] font-medium rounded-full">
                                {activeFilterCount}
                            </span>
                            <span className="text-[13px] text-gray-500 font-creato">
                                {activeFilterCount === 1 ? "filter" : "filters"} applied
                            </span>
                        </div>
                        <button
                            onClick={handleReset}
                            className="group flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-[#cd607f] hover:bg-[#cd607f]/5 rounded-lg transition-all duration-300"
                        >
                            <svg
                                width="14"
                                height="14"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                className="transform group-hover:rotate-90 transition-transform duration-300"
                            >
                                <path d="M18 6L6 18M6 6l12 12" strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                            <span className="text-[13px] font-creato font-medium">
                                Clear All
                            </span>
                        </button>
                    </div>
                )}
            </div>
        </section>
    );
};

export default LuxurySearchFilters;
