'use client';

/**
 * DispatchBookingBar Component
 * 
 * Uber-style on-demand beauty booking bar with pre-filled Emirate location,
 * dynamic service search with an absolute-positioned "🔥 Trending Services" dropdown,
 * and high-contrast "Book" action button.
 */

import React, { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { MapPin, Search, X, ChevronDown, Check } from 'lucide-react';

interface DispatchBookingBarProps {
  locale?: string;
  initialCity?: string;
}

export function DispatchBookingBar({
  locale = 'en',
  initialCity = 'Dubai',
}: DispatchBookingBarProps) {
  const router = useRouter();

  const [city, setCity] = useState(initialCity);
  const [isCityDropdownOpen, setIsCityDropdownOpen] = useState(false);
  const [serviceQuery, setServiceQuery] = useState('');
  const [isTrendingOpen, setIsTrendingOpen] = useState(false);

  const containerRef = useRef<HTMLDivElement>(null);
  const cityRef = useRef<HTMLDivElement>(null);

  const cities = ['Dubai', 'Abu Dhabi', 'Sharjah', 'Ajman', 'Ras Al Khaimah'];

  const trendingServices = [
    { name: 'Gel Manicure & Pedicure', category: 'Nails', icon: '💅', slug: 'nails' },
    { name: 'Salon Blowdry & Styling', category: 'Hair', icon: '💇‍♀️', slug: 'hair' },
    { name: 'Deep Tissue Massage (60m)', category: 'Massage', icon: '💆‍♀️', slug: 'massage' },
    { name: 'HydraFacial Glow Treatment', category: 'Facial', icon: '✨', slug: 'facial' },
    { name: 'Lash Extensions & Brow Lift', category: 'Lashes', icon: '👁️', slug: 'eyebrows' },
  ];

  // Close dropdowns on outside click
  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsTrendingOpen(false);
        setIsCityDropdownOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSelectTrending = (serviceName: string) => {
    setServiceQuery(serviceName);
    setIsTrendingOpen(false);
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const params = new URLSearchParams();
    if (serviceQuery.trim()) params.set('q', serviceQuery.trim());
    if (city) params.set('location', city);
    router.push(`/${locale}/search?${params.toString()}`);
  };

  return (
    <div ref={containerRef} className="relative w-full max-w-2xl">
      <form
        onSubmit={handleSearchSubmit}
        className="w-full bg-white rounded-2xl md:rounded-full p-2 md:p-2.5 shadow-xl border border-zinc-200/90 flex flex-col md:flex-row items-stretch md:items-center gap-2 md:gap-0 transition-all focus-within:ring-2 focus-within:ring-zinc-900/15 focus-within:border-zinc-900"
      >
        {/* ================= Input 1: Location (Pre-filled IP Emirate) ================= */}
        <div
          ref={cityRef}
          className="relative md:w-44 px-4 py-2 md:py-1 border-b md:border-b-0 md:border-e border-zinc-100 text-start"
        >
          <label className="block text-[10px] font-extrabold text-zinc-400 uppercase tracking-wider mb-0.5">
            Location
          </label>
          <button
            type="button"
            onClick={() => {
              setIsCityDropdownOpen((prev) => !prev);
              setIsTrendingOpen(false);
            }}
            className="w-full flex items-center justify-between gap-1.5 text-sm font-bold text-zinc-900 focus:outline-none text-start"
          >
            <span className="flex items-center gap-2 truncate">
              <MapPin className="w-4 h-4 text-zinc-400 flex-shrink-0" />
              <span className="truncate">{city}</span>
            </span>
            <ChevronDown className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
          </button>

          {/* City Selection Dropdown */}
          {isCityDropdownOpen && (
            <div className="absolute top-full inset-inline-start-0 w-48 mt-3 p-1.5 bg-white rounded-2xl shadow-2xl border border-zinc-100 z-50 animate-in fade-in slide-in-from-top-1 duration-150">
              <div className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider px-3 py-1.5">
                Select Emirate
              </div>
              <div className="space-y-0.5">
                {cities.map((c) => (
                  <button
                    key={c}
                    type="button"
                    onClick={() => {
                      setCity(c);
                      setIsCityDropdownOpen(false);
                    }}
                    className="w-full px-3 py-2 rounded-xl text-xs font-semibold text-zinc-800 hover:bg-zinc-50 flex items-center justify-between text-start transition-colors"
                  >
                    <span>{c}</span>
                    {city === c && <Check className="w-3.5 h-3.5 text-zinc-900" />}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* ================= Input 2: Dynamic Service Search ================= */}
        <div className="relative flex-1 px-4 py-2 md:py-1 text-start">
          <label className="block text-[10px] font-extrabold text-zinc-400 uppercase tracking-wider mb-0.5">
            Service
          </label>
          <div className="relative flex items-center gap-2">
            <Search className="w-4 h-4 text-zinc-400 flex-shrink-0" />
            <input
              type="text"
              value={serviceQuery}
              onChange={(e) => setServiceQuery(e.target.value)}
              onFocus={() => {
                setIsTrendingOpen(true);
                setIsCityDropdownOpen(false);
              }}
              placeholder="What service do you need?"
              className="w-full text-sm font-semibold text-zinc-900 placeholder:text-zinc-400 bg-transparent focus:outline-none truncate"
            />
            {serviceQuery && (
              <button
                type="button"
                onClick={() => setServiceQuery('')}
                className="text-zinc-400 hover:text-zinc-600 p-0.5"
              >
                <X className="w-3.5 h-3.5" />
              </button>
            )}
          </div>

          {/* ================= 🔥 Trending Services Floating Dropdown Panel ================= */}
          {isTrendingOpen && (
            <div className="absolute top-full inset-inline-start-0 w-full md:w-[380px] mt-3 p-3 bg-white rounded-2xl shadow-2xl border border-zinc-100 z-50 animate-in fade-in slide-in-from-top-1 duration-150 text-start">
              <div className="flex items-center justify-between px-2 pb-2 mb-1 border-b border-zinc-100">
                <span className="text-xs font-bold text-zinc-900 flex items-center gap-1.5">
                  <span>🔥</span>
                  <span>Trending Services in {city}</span>
                </span>
                <span className="text-[10px] font-semibold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">
                  Instant Match
                </span>
              </div>

              <div className="space-y-1">
                {trendingServices.map((item) => (
                  <button
                    key={item.name}
                    type="button"
                    onClick={() => handleSelectTrending(item.name)}
                    className="w-full px-3 py-2.5 rounded-xl hover:bg-zinc-50 flex items-center justify-between text-start transition-colors group"
                  >
                    <div className="flex items-center gap-2.5">
                      <span className="text-base flex-shrink-0">{item.icon}</span>
                      <div>
                        <p className="text-xs font-bold text-zinc-900 group-hover:text-brand-600 transition-colors">
                          {item.name}
                        </p>
                        <p className="text-[10px] text-zinc-400 font-medium">{item.category}</p>
                      </div>
                    </div>
                    <span className="text-[11px] font-semibold text-zinc-400 group-hover:text-zinc-900 transition-colors">
                      Select →
                    </span>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* ================= High-Contrast "Book" Action Button ================= */}
        <button
          type="submit"
          className="px-8 py-3.5 md:py-3.5 bg-zinc-950 hover:bg-black active:scale-98 text-white font-bold text-sm rounded-xl md:rounded-full shadow-md hover:shadow-lg transition-all flex items-center justify-center gap-2 flex-shrink-0"
        >
          <span>Book</span>
        </button>
      </form>
    </div>
  );
}
