'use client';

/**
 * DoorstepBookingBar Component
 * 
 * Clean, pill-shaped booking search bar for at-home / doorstep beauty services.
 * Features service dropdown, location selector with "Use my current location" GPS trigger,
 * and high-contrast "Find Pros" button.
 */

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

interface DoorstepBookingBarProps {
  locale?: string;
}

export function DoorstepBookingBar({ locale = 'en' }: DoorstepBookingBarProps) {
  const router = useRouter();

  const [selectedService, setSelectedService] = useState('blowdry');
  const [selectedLocation, setSelectedLocation] = useState('Dubai Marina & JBR');
  const [isLocationOpen, setIsLocationOpen] = useState(false);
  const [isLocating, setIsLocating] = useState(false);
  const [locationStatus, setLocationStatus] = useState<string | null>(null);

  const locationDropdownRef = useRef<HTMLDivElement>(null);

  const services = [
    { id: 'blowdry', label: 'Blowdry & Hair Styling' },
    { id: 'massage', label: 'Relaxing & Deep Tissue Massage' },
    { id: 'nails', label: 'Gel Manicure & Pedicure' },
    { id: 'facial', label: 'HydraFacial & Skincare' },
    { id: 'makeup', label: 'Event & Bridal Makeup' },
    { id: 'lashes', label: 'Lash Extensions & Brow Lift' },
    { id: 'waxing', label: 'Full Body Waxing' },
  ];

  const popularLocations = [
    'Dubai Marina & JBR',
    'Downtown Dubai & Business Bay',
    'Palm Jumeirah',
    'Arabian Ranches & Hills',
    'Jumeirah & Al Wasl',
    'Abu Dhabi (Corniche & Al Reem)',
    'Sharjah & Ajman',
  ];

  // Close location dropdown on click outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        locationDropdownRef.current &&
        !locationDropdownRef.current.contains(event.target as Node)
      ) {
        setIsLocationOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  /**
   * Browser Geolocation trigger for "📍 Use my current location"
   */
  const handleBrowserLocation = () => {
    if (!navigator.geolocation) {
      setLocationStatus('Geolocation is not supported by your browser');
      return;
    }

    setIsLocating(true);
    setLocationStatus('Locating your doorstep...');

    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        // In production: Reverse-geocode via API. For UI demo: resolve to nearby doorstep area
        setTimeout(() => {
          setSelectedLocation(`Near you (${latitude.toFixed(2)}°, ${longitude.toFixed(2)}°)`);
          setIsLocating(false);
          setIsLocationOpen(false);
          setLocationStatus(null);
        }, 600);
      },
      (error) => {
        setIsLocating(false);
        setLocationStatus('Location access denied. Please select your area.');
        console.warn('Browser geolocation error:', error.message);
      },
      { timeout: 8000 }
    );
  };

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

  return (
    <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/10 focus-within:border-zinc-900"
    >
      {/* 1. Service Dropdown Input */}
      <div className="flex-1 px-4 py-2.5 md:py-1 border-b md:border-b-0 md:border-e border-zinc-100 text-start">
        <label className="block text-[11px] font-bold text-zinc-500 uppercase tracking-wider mb-0.5">
          Treatment / Service
        </label>
        <div className="relative flex items-center gap-2">
          <Sparkles className="w-4 h-4 text-zinc-400 flex-shrink-0" />
          <select
            value={selectedService}
            onChange={(e) => setSelectedService(e.target.value)}
            className="w-full text-sm font-semibold text-zinc-900 bg-transparent focus:outline-none cursor-pointer appearance-none pe-6 truncate"
          >
            {services.map((s) => (
              <option key={s.id} value={s.id}>
                {s.label}
              </option>
            ))}
          </select>
          <ChevronDown className="w-3.5 h-3.5 text-zinc-400 absolute end-0 pointer-events-none" />
        </div>
      </div>

      {/* 2. Location Selector with Geolocation */}
      <div
        ref={locationDropdownRef}
        className="flex-1 relative px-4 py-2.5 md:py-1 border-b md:border-b-0 md:border-e border-zinc-100 text-start"
      >
        <label className="block text-[11px] font-bold text-zinc-500 uppercase tracking-wider mb-0.5">
          Your Doorstep Location
        </label>
        <button
          type="button"
          onClick={() => setIsLocationOpen((prev) => !prev)}
          className="w-full flex items-center justify-between gap-2 text-sm font-semibold 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">{selectedLocation}</span>
          </span>
          <ChevronDown className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
        </button>

        {/* Location Dropdown Menu */}
        {isLocationOpen && (
          <div className="absolute top-full inset-inline-start-0 w-full min-w-[260px] mt-3 p-2 bg-white rounded-2xl shadow-2xl border border-zinc-100 z-50 animate-in fade-in slide-in-from-top-1 duration-150">
            {/* 📍 Use my current location Button */}
            <button
              type="button"
              onClick={handleBrowserLocation}
              disabled={isLocating}
              className="w-full px-3.5 py-2.5 rounded-xl bg-zinc-50 hover:bg-zinc-100 active:bg-zinc-200 text-zinc-900 text-xs font-bold flex items-center justify-between gap-2 transition-colors mb-2 text-start border border-zinc-200/60"
            >
              <span className="flex items-center gap-2">
                <Navigation className={`w-3.5 h-3.5 text-brand-600 ${isLocating ? 'animate-spin' : ''}`} />
                <span>{isLocating ? 'Detecting doorstep...' : '📍 Use my current location'}</span>
              </span>
              <span className="text-[10px] text-zinc-400 font-mono">GPS</span>
            </button>

            {locationStatus && (
              <p className="text-[11px] text-amber-600 px-3 py-1 mb-1 font-medium">
                {locationStatus}
              </p>
            )}

            <div className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider px-3 py-1">
              Select UAE Area
            </div>

            <div className="space-y-0.5 max-h-48 overflow-y-auto">
              {popularLocations.map((loc) => (
                <button
                  key={loc}
                  type="button"
                  onClick={() => {
                    setSelectedLocation(loc);
                    setIsLocationOpen(false);
                  }}
                  className="w-full px-3 py-2 rounded-lg text-xs font-medium text-zinc-800 hover:bg-zinc-50 flex items-center justify-between text-start transition-colors"
                >
                  <span className="truncate">{loc}</span>
                  {selectedLocation === loc && (
                    <Check className="w-3.5 h-3.5 text-zinc-900 flex-shrink-0" />
                  )}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

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