'use client';

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

// ─── Types ─────────────────────────────────────────────────────
type SearchTab = 'BUY' | 'RENT' | 'OFF-PLAN';

interface Suggestion {
  label: string;
  type: 'location' | 'project' | 'developer' | 'property';
}

// ─── Constants ─────────────────────────────────────────────────
const HERO_STATS = [
  { value: '5,000+', label: 'Properties' },
  { value: '200+',   label: 'Verified Agents' },
  { value: '50+',    label: 'Developers' },
];

const RESIDENTIAL_TYPES = ['apartment', 'villa', 'penthouse', 'townhouse'];

const TYPE_ICON: Record<Suggestion['type'], string> = {
  location:  '📍',
  project:   '🏗️',
  developer: '🏢',
  property:  '🏠',
};

const TYPE_LABEL: Record<Suggestion['type'], string> = {
  location:  'Location',
  project:   'Project',
  developer: 'Developer',
  property:  'Property',
};

// ─── Debounce hook ─────────────────────────────────────────────
function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounced;
}

// ─── Component ─────────────────────────────────────────────────
export function HeroSection() {
  const router = useRouter();

  // Form state
  const [activeTab, setActiveTab]       = useState<SearchTab>('BUY');
  const [location, setLocation]         = useState('');
  const [propertyType, setPropertyType] = useState('');
  const [beds, setBeds]                 = useState('any');
  const [priceRange, setPriceRange]     = useState('any');

  // Autocomplete state
  const [suggestions, setSuggestions]       = useState<Suggestion[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [isLoading, setIsLoading]           = useState(false);
  const [activeIndex, setActiveIndex]       = useState(-1);

  const inputRef      = useRef<HTMLInputElement>(null);
  const dropdownRef   = useRef<HTMLDivElement>(null);
  const debounced     = useDebounce(location, 280);

  const shouldShowBeds = RESIDENTIAL_TYPES.includes(propertyType.toLowerCase());

  // ── Fetch suggestions ────────────────────────────────────────
  const fetchSuggestions = useCallback(async (q: string) => {
    if (q.length < 2) {
      setSuggestions([]);
      setShowSuggestions(false);
      return;
    }
    setIsLoading(true);
    try {
      const res  = await fetch(`/api/properties/suggestions?q=${encodeURIComponent(q)}`);
      const json = await res.json();
      if (json.success && Array.isArray(json.data)) {
        setSuggestions(json.data);
        setShowSuggestions(json.data.length > 0);
        setActiveIndex(-1);
      }
    } catch {
      // fail silently — autocomplete is enhancement-only
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchSuggestions(debounced);
  }, [debounced, fetchSuggestions]);

  // ── Close dropdown on outside click ─────────────────────────
  useEffect(() => {
    function onOutsideClick(e: MouseEvent) {
      if (
        dropdownRef.current && !dropdownRef.current.contains(e.target as Node) &&
        inputRef.current  && !inputRef.current.contains(e.target as Node)
      ) {
        setShowSuggestions(false);
        setActiveIndex(-1);
      }
    }
    document.addEventListener('mousedown', onOutsideClick);
    return () => document.removeEventListener('mousedown', onOutsideClick);
  }, []);

  // ── Keyboard navigation ──────────────────────────────────────
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (!showSuggestions) {
      if (e.key === 'Enter') handleSearch();
      return;
    }
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveIndex(i => Math.min(i + 1, suggestions.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveIndex(i => Math.max(i - 1, -1));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (activeIndex >= 0) {
        selectSuggestion(suggestions[activeIndex]);
      } else {
        handleSearch();
      }
    } else if (e.key === 'Escape') {
      setShowSuggestions(false);
      setActiveIndex(-1);
    }
  };

  const selectSuggestion = (s: Suggestion) => {
    setLocation(s.label);
    setShowSuggestions(false);
    setActiveIndex(-1);
    inputRef.current?.focus();
  };

  // ── Search submit ────────────────────────────────────────────
  const handleSearch = () => {
    const params = new URLSearchParams();
    if (activeTab === 'RENT')     params.set('type', 'rent');
    if (activeTab === 'OFF-PLAN') params.set('type', 'offplan');
    if (location)                 params.set('location', location);
    if (propertyType)             params.set('category', propertyType);
    if (beds !== 'any')           params.set('bedrooms', beds);
    if (priceRange !== 'any')     params.set('price_range', priceRange);
    router.push(`/listings?${params.toString()}`);
  };

  // ── Clear input ──────────────────────────────────────────────
  const clearLocation = () => {
    setLocation('');
    setSuggestions([]);
    setShowSuggestions(false);
    inputRef.current?.focus();
  };

  return (
    <section
      id="hero"
      className="relative h-screen min-h-[700px] flex items-center justify-center overflow-hidden"
    >
      {/* ── Background Image ──────────────────────────────── */}
      <div className="absolute inset-0 z-0">
        <div className="relative w-full h-full">
          <Image
            src="https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=1920&q=80"
            alt="Dubai skyline at golden hour"
            fill
            className="object-cover object-center"
            priority
          />
        </div>
        <div className="absolute inset-0 bg-gradient-to-b from-[#0d1c32]/65 via-[#0d1c32]/30 to-[#0d1c32]/75" />
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,transparent_40%,rgba(13,28,50,0.4)_100%)]" />
      </div>

      {/* ── Content ───────────────────────────────────────── */}
      <div className="relative z-10 w-full max-w-7xl mx-auto px-6 md:px-12 grid grid-cols-1 lg:grid-cols-12 gap-12 items-center">

        {/* Left Column: Hero Text */}
        <div className="lg:col-span-7 text-left flex flex-col items-start">
          {/* Eyebrow badge */}
          <div className="inline-flex items-center gap-2.5 px-5 py-2 rounded-full
            bg-white/10 backdrop-blur-sm border border-white/20 mb-8 animate-fade-in-up">
            <span className="w-1.5 h-1.5 rounded-full bg-[#098E4B] animate-pulse flex-shrink-0" />
            <span className="text-white/90 text-[11px] font-bold tracking-[0.2em] uppercase">
              RERA &amp; DLD Compliant Platform
            </span>
          </div>

          {/* Headline */}
          <h1
            className="font-serif font-bold text-white leading-tight mb-6 text-shadow
              text-5xl sm:text-6xl md:text-7xl animate-fade-in-up"
            style={{ animationDelay: '0.1s' }}
          >
            Find Your Wild<br />
            <span className="text-[#098E4B]">Sanctuary</span>
          </h1>

          <p className="text-white/90 text-lg md:text-xl font-medium mb-10 max-w-xl leading-relaxed text-shadow">
            Exclusive properties, unparalleled service, and expert advisory in Dubai&apos;s premier residential enclaves.
          </p>

          {/* Stats row */}
          <div className="flex items-center gap-8 sm:gap-12 animate-fade-in-up" style={{ animationDelay: '0.35s' }}>
            {HERO_STATS.map(({ value, label }, i) => (
              <div key={label} className="flex items-center gap-8 sm:gap-12">
                <div className="text-left">
                  <div className="text-2xl sm:text-3xl font-bold text-[#098E4B]">{value}</div>
                  <div className="text-white/55 text-[10px] uppercase tracking-widest mt-1">{label}</div>
                </div>
                {i < HERO_STATS.length - 1 && (
                  <div className="w-px h-8 bg-white/15 hidden sm:block" />
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Right Column: Search Form */}
        <div className="lg:col-span-5 w-full flex justify-center lg:justify-end">
          <div className="w-full max-w-md bg-white/10 backdrop-blur-xl border border-white/20 p-6 lg:p-8 rounded-2xl shadow-2xl flex flex-col justify-between aspect-square">

            {/* Step 1: Search Tabs */}
            <div className="flex border-b border-white/10 pb-2 gap-6">
              {(['Buy', 'Rent', 'Off-Plan'] as const).map((tab) => {
                const tabValue = tab.toUpperCase() as SearchTab;
                const isActive = activeTab === tabValue;
                return (
                  <button
                    key={tab}
                    onClick={() => setActiveTab(tabValue)}
                    className={`pb-2 text-sm font-semibold tracking-wide transition-all relative ${
                      isActive ? 'text-[#098E4B]' : 'text-white/60 hover:text-white'
                    }`}
                  >
                    {tab}
                    {isActive && <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#098E4B]" />}
                  </button>
                );
              })}
            </div>

            {/* Step 2: Input Fields */}
            <div className="space-y-4 my-auto">

              {/* ── Location / Autocomplete ── */}
              <div className="relative">
                <label className="block text-xs text-white/70 font-medium uppercase tracking-wider mb-1.5">
                  Location
                </label>

                {/* Input wrapper */}
                <div className="relative flex items-center">
                  <MapPin className="absolute left-3 w-4 h-4 text-white/40 pointer-events-none flex-shrink-0" />
                  <input
                    ref={inputRef}
                    type="text"
                    value={location}
                    onChange={(e) => setLocation(e.target.value)}
                    onKeyDown={handleKeyDown}
                    onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
                    placeholder="City, neighborhood or building..."
                    autoComplete="off"
                    className="w-full bg-white/5 border border-white/10 rounded-xl pl-9 pr-9 py-3 text-sm text-white
                      placeholder-white/40 focus:outline-none focus:border-[#098E4B] transition-all"
                  />
                  {/* Right-side spinner or clear button */}
                  <div className="absolute right-3 flex items-center">
                    {isLoading ? (
                      <Loader2 className="w-4 h-4 text-white/40 animate-spin" />
                    ) : location ? (
                      <button
                        type="button"
                        onClick={clearLocation}
                        className="w-4 h-4 text-white/40 hover:text-white transition-colors"
                        aria-label="Clear location"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    ) : null}
                  </div>
                </div>

                {/* ── Suggestions Dropdown ── */}
                {showSuggestions && (
                  <div
                    ref={dropdownRef}
                    role="listbox"
                    aria-label="Location suggestions"
                    className="absolute top-full left-0 right-0 mt-1.5 z-50
                      bg-neutral-900 border border-white/10 rounded-xl shadow-2xl
                      overflow-hidden animate-fade-in-up"
                    style={{ animationDuration: '0.15s' }}
                  >
                    {suggestions.map((s, idx) => {
                      const isActive = idx === activeIndex;
                      return (
                        <button
                          key={`${s.type}-${s.label}`}
                          role="option"
                          aria-selected={isActive}
                          type="button"
                          onMouseDown={(e) => {
                            // mousedown fires before blur, so we prevent blur then select
                            e.preventDefault();
                            selectSuggestion(s);
                          }}
                          onMouseEnter={() => setActiveIndex(idx)}
                          className={`w-full flex items-center gap-3 px-4 py-2.5 text-sm text-left transition-colors
                            ${isActive
                              ? 'bg-[#098E4B]/20 text-white'
                              : 'text-white/80 hover:bg-white/5 hover:text-white'
                            }
                            ${idx < suggestions.length - 1 ? 'border-b border-white/5' : ''}
                          `}
                        >
                          {/* Type icon */}
                          <span className="text-base leading-none flex-shrink-0">{TYPE_ICON[s.type]}</span>

                          {/* Label — highlight matching portion */}
                          <span className="flex-1 truncate font-medium">
                            {highlightMatch(s.label, location)}
                          </span>

                          {/* Type badge */}
                          <span className={`text-[9px] font-bold uppercase tracking-widest px-1.5 py-0.5 rounded flex-shrink-0
                            ${isActive ? 'bg-[#098E4B]/40 text-white' : 'bg-white/10 text-white/50'}`}>
                            {TYPE_LABEL[s.type]}
                          </span>
                        </button>
                      );
                    })}

                    {/* Footer hint */}
                    <div className="px-4 py-2 border-t border-white/10 flex items-center gap-1.5">
                      <span className="text-[10px] text-white/30 font-mono">↑↓ navigate</span>
                      <span className="text-[10px] text-white/30">·</span>
                      <span className="text-[10px] text-white/30 font-mono">↵ select</span>
                      <span className="text-[10px] text-white/30">·</span>
                      <span className="text-[10px] text-white/30 font-mono">esc close</span>
                    </div>
                  </div>
                )}
              </div>

              {/* ── Property Type + Beds (conditional) ── */}
              <div className={`grid gap-3 transition-all duration-300 ${shouldShowBeds ? 'grid-cols-2' : 'grid-cols-1'}`}>
                <div>
                  <label className="block text-xs text-white/70 font-medium uppercase tracking-wider mb-1.5">Property Type</label>
                  <select
                    value={propertyType}
                    onChange={(e) => {
                      setPropertyType(e.target.value);
                      if (!RESIDENTIAL_TYPES.includes(e.target.value.toLowerCase())) {
                        setBeds('any');
                      }
                    }}
                    className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-3 text-sm text-white/90
                      focus:outline-none focus:border-[#098E4B] transition-all appearance-none cursor-pointer"
                  >
                    <option value="" className="bg-neutral-900 text-white">Any Type</option>
                    <option value="villa" className="bg-neutral-900 text-white">Villa</option>
                    <option value="penthouse" className="bg-neutral-900 text-white">Penthouse</option>
                    <option value="apartment" className="bg-neutral-900 text-white">Apartment</option>
                    <option value="townhouse" className="bg-neutral-900 text-white">Townhouse</option>
                    <option value="commercial" className="bg-neutral-900 text-white">Commercial</option>
                  </select>
                </div>

                {shouldShowBeds && (
                  <div className="animate-fade-in-up" style={{ animationDuration: '0.2s' }}>
                    <label className="block text-xs text-white/70 font-medium uppercase tracking-wider mb-1.5">Beds &amp; Baths</label>
                    <select
                      value={beds}
                      onChange={(e) => setBeds(e.target.value)}
                      className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-3 text-sm text-white/90
                        focus:outline-none focus:border-[#098E4B] transition-all appearance-none cursor-pointer"
                    >
                      <option value="any" className="bg-neutral-900 text-white">Any Beds</option>
                      <option value="1" className="bg-neutral-900 text-white">1+ Beds</option>
                      <option value="2" className="bg-neutral-900 text-white">2+ Beds</option>
                      <option value="3" className="bg-neutral-900 text-white">3+ Beds</option>
                      <option value="4" className="bg-neutral-900 text-white">4+ Beds</option>
                    </select>
                  </div>
                )}
              </div>

              {/* ── Budget Range ── */}
              <div>
                <label className="block text-xs text-white/70 font-medium uppercase tracking-wider mb-1.5">Budget Range</label>
                <select
                  value={priceRange}
                  onChange={(e) => setPriceRange(e.target.value)}
                  className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm text-white/90
                    focus:outline-none focus:border-[#098E4B] transition-all appearance-none cursor-pointer"
                >
                  <option value="any" className="bg-neutral-900 text-white">Any Price (AED)</option>
                  <option value="0-1000000" className="bg-neutral-900 text-white">Up to 1,000,000</option>
                  <option value="1000000-5000000" className="bg-neutral-900 text-white">1,000,000 – 5,000,000</option>
                  <option value="5000000+" className="bg-neutral-900 text-white">5,000,000+</option>
                </select>
              </div>
            </div>

            {/* Step 3: Submit */}
            <button
              onClick={handleSearch}
              className="w-full bg-[#098E4B] hover:bg-[#077a3f] text-white text-sm font-bold tracking-wider uppercase
                py-4 rounded-xl transition-all duration-300 hover:shadow-[0_0_20px_rgba(9,142,75,0.4)]
                transform hover:scale-[1.01]"
            >
              Search Properties
            </button>
          </div>
        </div>
      </div>

      {/* Scroll cue */}
      <div className="absolute bottom-8 left-1/2 -translate-x-1/2 flex flex-col items-center gap-1 animate-bounce">
        <div className="w-px h-10 bg-gradient-to-b from-white/50 to-transparent" />
      </div>
    </section>
  );
}

// ─── Highlight matching substring ──────────────────────────────
function highlightMatch(text: string, query: string): React.ReactNode {
  if (!query) return text;
  const idx = text.toLowerCase().indexOf(query.toLowerCase());
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <span className="text-[#098E4B] font-bold">{text.slice(idx, idx + query.length)}</span>
      {text.slice(idx + query.length)}
    </>
  );
}
