'use client';

/**
 * PremiumBookingBar
 *
 * Sleek, horizontal pill-shaped booking engine with:
 * - Standard 3 Emirates selector: Dubai (default), Sharjah, Ajman with Location label
 * - Service search input with Service label & Dynamic Typewriter placeholder
 * - Full page dim & subtle blur backdrop overlay when focused on search
 * - Live Category Pills (routing to /[locale]/categories/[slug])
 * - Live Trending Services with real thumbnails & PriceDisplay (routing to /[locale]/services/[slug])
 * - Live Typeahead Search
 * - Search form submitting to `/${locale}/services?q=...`
 */

import React, { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import type { Variants } from 'framer-motion';
import {
  MapPin,
  ChevronDown,
  Check,
  X,
  Flame,
  Search,
} from 'lucide-react';
import { PriceDisplay } from '../PriceDisplay';
import { ImageWithFallback } from '@/components/ui/ImageWithFallback';
import { categoryService, serviceService } from '@/lib/api/client';
import type { Category, Service } from '@shinecode/api-client/types';

export interface PremiumBookingBarProps {
  locale?: string;
  initialCity?: string;
  initialCategories?: Category[];
  initialTrendingServices?: Service[];
  allServices?: Service[];
}

/* High-intent doorstep service placeholders for Typewriter */
const PLACEHOLDERS = [
  'What service can we bring to you?',
  'Need a flawless Gelish Pedicure?',
  'Book a relaxing Hot Stone Massage...',
  'Ready for a Lash Lift & Lamination?',
  'Try a Russian Gel Manicure...',
  'Looking for a Couples Spa day?',
];

/* Standard 3 Emirates */
const UAE_EMIRATES = ['Dubai', 'Sharjah', 'Ajman'];

const dropdownVariants: Variants = {
  hidden: { opacity: 0, y: -6, scale: 0.98 },
  visible: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { duration: 0.18, ease: 'easeOut' },
  },
  exit: {
    opacity: 0,
    y: -4,
    scale: 0.98,
    transition: { duration: 0.12 },
  },
};

/**
 * Custom Typewriter Hook
 */
function useTypewriter(
  phrases: string[],
  typingSpeed: number = 90,
  deletingSpeed: number = 45,
  pauseDuration: number = 2000
) {
  const [displayText, setDisplayText] = useState(phrases[0] || '');
  const [phraseIndex, setPhraseIndex] = useState(0);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    let timer: NodeJS.Timeout;
    const currentPhrase = phrases[phraseIndex % phrases.length];

    if (!isDeleting) {
      // Typing phase
      if (displayText.length < currentPhrase.length) {
        timer = setTimeout(() => {
          setDisplayText(currentPhrase.slice(0, displayText.length + 1));
        }, typingSpeed);
      } else {
        // Fully typed: pause for 2000ms
        timer = setTimeout(() => {
          setIsDeleting(true);
        }, pauseDuration);
      }
    } else {
      // Deleting phase
      if (displayText.length > 0) {
        timer = setTimeout(() => {
          setDisplayText(currentPhrase.slice(0, displayText.length - 1));
        }, deletingSpeed);
      } else {
        // Fully deleted: advance to next phrase and start typing
        timer = setTimeout(() => {
          setIsDeleting(false);
          setPhraseIndex((prev) => (prev + 1) % phrases.length);
        }, 300);
      }
    }

    return () => clearTimeout(timer);
  }, [displayText, isDeleting, phraseIndex, phrases, typingSpeed, deletingSpeed, pauseDuration]);

  return displayText;
}

export function PremiumBookingBar({
  locale = 'en',
  initialCity = 'Dubai',
  initialCategories = [],
  initialTrendingServices = [],
  allServices: initialAllServices = [],
}: PremiumBookingBarProps) {
  const router = useRouter();
  const [selectedCity, setSelectedCity] = useState(initialCity);
  const [isCityOpen, setIsCityOpen] = useState(false);
  const [serviceQuery, setServiceQuery] = useState('');
  const [searchResults, setSearchResults] = useState<Service[]>([]);
  const [isTrendingOpen, setIsTrendingOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // Live Data State
  const [categories, setCategories] = useState<Category[]>(initialCategories);
  const [trendingServices, setTrendingServices] = useState<Service[]>(initialTrendingServices);
  const [allServices, setAllServices] = useState<Service[]>(initialAllServices);

  // Dynamic Typewriter Animated Placeholder
  const animatedPlaceholder = useTypewriter(PLACEHOLDERS, 90, 45, 2000);

  // Fetch live API data if not supplied via props
  useEffect(() => {
    let isMounted = true;

    async function loadData() {
      try {
        const [catRes, topRes, allRes] = await Promise.all([
          initialCategories.length > 0
            ? Promise.resolve({ ok: true, data: initialCategories })
            : categoryService.getCategories({ per_page: 8 }),
          initialTrendingServices.length > 0
            ? Promise.resolve({ ok: true, data: initialTrendingServices })
            : serviceService.getTopRatedServices(6),
          initialAllServices.length > 0
            ? Promise.resolve({ ok: true, data: initialAllServices })
            : serviceService.getServices(),
        ]);

        if (isMounted) {
          if (catRes.ok && Array.isArray(catRes.data) && catRes.data.length > 0) {
            setCategories(catRes.data);
          }
          if (topRes.ok && Array.isArray(topRes.data) && topRes.data.length > 0) {
            setTrendingServices(topRes.data);
          }
          if (allRes.ok && Array.isArray(allRes.data) && allRes.data.length > 0) {
            setAllServices(allRes.data);
          }
        }
      } catch (err) {
        console.error('[PremiumBookingBar] Error fetching live data:', err);
      }
    }

    loadData();

    return () => {
      isMounted = false;
    };
  }, [initialCategories, initialTrendingServices, initialAllServices]);

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

  // Bulletproof Search Logic (Case-Insensitive)
  const handleSearch = (query: string) => {
    setServiceQuery(query);
    if (query.trim().length < 2) {
      setSearchResults([]);
      return;
    }
    const lowerQuery = query.toLowerCase().trim();
    const filtered = allServices.filter((service) => {
      const matchName = service.name?.toLowerCase().includes(lowerQuery);
      const matchCat = (
        service.category_name || (service as unknown as { category?: { name?: string } }).category?.name
      )
        ?.toLowerCase()
        .includes(lowerQuery);
      return matchName || matchCat;
    });
    setSearchResults(filtered.slice(0, 5));
  };

  const handleSelectCity = (cityName: string) => {
    setSelectedCity(cityName);
    setIsCityOpen(false);
  };

  const handleSelectService = (item: Service) => {
    setIsTrendingOpen(false);
    router.push(`/${locale}/services/${item.slug || item.id}`);
  };

  const handleBook = (e: React.FormEvent) => {
    e.preventDefault();
    setIsTrendingOpen(false);
    setIsCityOpen(false);
    if (serviceQuery.trim()) {
      router.push(`/${locale}/services?q=${encodeURIComponent(serviceQuery.trim())}`);
    } else {
      router.push(`/${locale}/services`);
    }
  };

  const isAr = locale === 'ar';
  const isSearching = serviceQuery.trim().length >= 2;

  // Helper to extract service image URL
  const getServiceThumbnail = (service: Service): string => {
    if (service.attchments && service.attchments.length > 0 && service.attchments[0]) {
      const first = service.attchments[0];
      if (typeof first === 'string') return first;
      if (typeof first === 'object' && first && 'url' in first && typeof first.url === 'string') {
        return first.url;
      }
    }
    const fallbackImage =
      (service as unknown as { image?: string; thumbnail?: string }).image ||
      (service as unknown as { thumbnail?: string }).thumbnail;
    if (fallbackImage) return fallbackImage;
    return '/images/fallback-placeholder.svg';
  };

  return (
    <>
      {/* ── Dim & Subtle Blur Backdrop Overlay when searching/focused ── */}
      <AnimatePresence>
        {(isTrendingOpen || isCityOpen) && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            onClick={() => {
              setIsTrendingOpen(false);
              setIsCityOpen(false);
            }}
            className="fixed inset-0 bg-black/40 backdrop-blur-xs z-40"
          />
        )}
      </AnimatePresence>

      <div ref={containerRef} className="relative z-50 w-full max-w-xl">
        <form
          onSubmit={handleBook}
          className="relative z-50 bg-white dark:bg-zinc-900 border border-zinc-100 dark:border-zinc-800 rounded-2xl md:rounded-full shadow-xl shadow-black/5 dark:shadow-black/20 p-2 md:p-1.5 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-950/10 dark:focus-within:ring-white/10 focus-within:border-zinc-300 dark:focus-within:border-zinc-700"
        >
          {/* ── Location Block ── */}
          <div className="relative md:w-44 px-3 py-2 md:py-1 border-b md:border-b-0 md:border-e border-zinc-100 dark:border-zinc-800 text-start shrink-0">
            <label className="block text-[10px] font-extrabold text-zinc-400 dark:text-zinc-500 uppercase tracking-wider mb-0.5">
              {isAr ? 'المدينة' : 'Location'}
            </label>

            <button
              type="button"
              onClick={() => {
                setIsCityOpen((prev) => !prev);
                setIsTrendingOpen(false);
              }}
              className="flex items-center justify-between gap-1.5 w-full text-sm font-bold text-zinc-900 dark:text-white focus:outline-none cursor-pointer"
            >
              <span className="flex items-center gap-1.5 truncate">
                <MapPin className="w-4 h-4 text-zinc-500 shrink-0" />
                <span className="truncate">{selectedCity}</span>
              </span>
              <ChevronDown
                className={`w-3.5 h-3.5 text-zinc-400 shrink-0 transition-transform duration-200 ${
                  isCityOpen ? 'rotate-180 text-zinc-900 dark:text-white' : ''
                }`}
              />
            </button>

            <AnimatePresence>
              {isCityOpen && (
                <motion.div
                  variants={dropdownVariants}
                  initial="hidden"
                  animate="visible"
                  exit="exit"
                  className="absolute top-full inset-inline-start-0 mt-3 w-48 bg-white dark:bg-zinc-900 rounded-2xl border border-zinc-100 dark:border-zinc-800 shadow-xl shadow-black/5 dark:shadow-black/30 p-1.5 z-[100] origin-top-start text-start"
                >
                  <p className="text-[10px] font-black text-zinc-400 uppercase tracking-widest px-3 py-1.5">
                    {isAr ? 'اختر الإمارة' : 'Select Emirate'}
                  </p>

                  <div className="space-y-0.5">
                    {UAE_EMIRATES.map((city) => (
                      <button
                        key={city}
                        type="button"
                        onClick={() => handleSelectCity(city)}
                        className="w-full px-3 py-2 rounded-xl flex items-center justify-between text-xs font-bold text-zinc-800 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors text-start cursor-pointer"
                      >
                        <span>{city}</span>
                        {selectedCity === city && (
                          <Check className="w-3.5 h-3.5 text-zinc-950 dark:text-white shrink-0" />
                        )}
                      </button>
                    ))}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* ── Service Block ── */}
          <div className="relative flex-1 min-w-0 px-3 py-2 md:py-1 text-start">
            <label className="block text-[10px] font-extrabold text-zinc-400 dark:text-zinc-500 uppercase tracking-wider mb-0.5">
              {isAr ? 'الخدمة' : 'Service'}
            </label>
            <div className="flex items-center gap-2">
              <Search className="w-4 h-4 text-zinc-400 shrink-0" />
              <input
                type="text"
                value={serviceQuery}
                onChange={(e) => {
                  handleSearch(e.target.value);
                  if (!isTrendingOpen) setIsTrendingOpen(true);
                }}
                onFocus={() => {
                  setIsTrendingOpen(true);
                  setIsCityOpen(false);
                }}
                placeholder={animatedPlaceholder}
                className="w-full text-sm font-semibold text-zinc-900 dark:text-white placeholder:text-zinc-400 dark:placeholder:text-zinc-500 bg-transparent focus:outline-none truncate"
              />
              {serviceQuery && (
                <button
                  type="button"
                  onClick={() => {
                    setServiceQuery('');
                    setSearchResults([]);
                  }}
                  className="text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 p-0.5 shrink-0 cursor-pointer"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              )}
            </div>

            <AnimatePresence>
              {isTrendingOpen && (
                <motion.div
                  variants={dropdownVariants}
                  initial="hidden"
                  animate="visible"
                  exit="exit"
                  className="absolute top-full inset-inline-start-0 mt-3 w-full md:w-[380px] bg-white dark:bg-zinc-900 rounded-2xl border border-zinc-100 dark:border-zinc-800 shadow-2xl p-3.5 z-[100] origin-top-start"
                >
                  {/* ── 1. Top Section: Categories ── */}
                  <div className="pb-3 mb-3 border-b border-zinc-100 dark:border-zinc-800">
                    <p className="text-xs uppercase text-zinc-400 dark:text-zinc-500 font-semibold mb-2 px-1">
                      {isAr ? 'التصنيفات' : 'Categories'}
                    </p>
                    <div className="flex flex-wrap gap-2 px-1">
                      {categories.slice(0, 6).map((cat) => (
                        <Link
                          key={cat.id}
                          href={`/${locale}/categories/${cat.slug || cat.id}`}
                          onClick={() => setIsTrendingOpen(false)}
                          className="border border-zinc-200 dark:border-zinc-700 rounded-full px-3 py-1 text-xs font-semibold text-zinc-700 dark:text-zinc-300 hover:bg-zinc-50 dark:hover:bg-zinc-800 hover:border-zinc-300 dark:hover:border-zinc-600 transition-colors cursor-pointer"
                        >
                          {cat.name}
                        </Link>
                      ))}
                    </div>
                  </div>

                  {/* ── 2. Bottom Section: Search Results OR Trending Services ── */}
                  <div>
                    {isSearching ? (
                      // Live Search Results
                      <>
                        <div className="flex items-center justify-between text-xs uppercase text-zinc-400 dark:text-zinc-500 font-semibold mb-1.5 px-1">
                          <div className="flex items-center gap-1">
                            <Search className="w-3.5 h-3.5 text-brand-500 shrink-0" />
                            <span>
                              {isAr ? 'نتائج البحث' : 'Search Results'} ({searchResults.length})
                            </span>
                          </div>
                        </div>

                        {searchResults.length > 0 ? (
                          <div className="space-y-1 max-h-60 overflow-y-auto pr-1">
                            {searchResults.map((item) => (
                              <button
                                key={item.id}
                                type="button"
                                onClick={() => handleSelectService(item)}
                                className="w-full p-2 rounded-xl flex items-center justify-between text-start hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors group cursor-pointer gap-2"
                              >
                                <div className="flex items-center gap-2.5 min-w-0 flex-1">
                                  <div className="relative w-8 h-8 rounded-lg overflow-hidden shrink-0 bg-zinc-100 dark:bg-zinc-800 border border-zinc-200/60 dark:border-zinc-700">
                                    <ImageWithFallback
                                      src={getServiceThumbnail(item)}
                                      fallbackSrc="/images/fallback-placeholder.svg"
                                      alt={item.name}
                                      fill
                                      sizes="32px"
                                      className="object-cover w-full h-full"
                                    />
                                  </div>
                                  <div className="min-w-0 flex-1">
                                    <p className="text-xs font-bold text-zinc-800 dark:text-zinc-200 truncate group-hover:text-brand-600 dark:group-hover:text-brand-400 transition-colors">
                                      {item.name}
                                    </p>
                                    <span className="text-[10px] text-zinc-400 font-medium">
                                      {item.category_name || (isAr ? 'خدمة' : 'Service')}
                                    </span>
                                  </div>
                                </div>

                                <div className="shrink-0 text-end">
                                  <PriceDisplay
                                    amount={item.discount_price ?? item.price}
                                    className="text-xs font-extrabold text-zinc-900 dark:text-white"
                                    iconClassName="w-2.5 h-2.5 mr-0.5 inline-block text-brand-500"
                                  />
                                </div>
                              </button>
                            ))}
                          </div>
                        ) : (
                          <div className="py-3 px-2 text-center text-xs text-zinc-500">
                            <p>
                              {isAr
                                ? `لم يتم العثور على خدمات تطابق "${serviceQuery}"`
                                : `No services found matching "${serviceQuery}"`}
                            </p>
                          </div>
                        )}
                      </>
                    ) : (
                      // Default Trending Now
                      <>
                        <div className="flex items-center gap-1 text-xs uppercase text-zinc-400 dark:text-zinc-500 font-semibold mb-1.5 px-1">
                          <Flame className="w-3.5 h-3.5 text-brand-500 fill-brand-500 shrink-0" />
                          <span>{isAr ? 'الأكثر طلباً' : 'Trending Now'}</span>
                        </div>

                        <div className="space-y-1 max-h-60 overflow-y-auto pr-1">
                          {trendingServices.slice(0, 4).map((item) => (
                            <button
                              key={item.id}
                              type="button"
                              onClick={() => handleSelectService(item)}
                              className="w-full p-2 rounded-xl flex items-center justify-between text-start hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors group cursor-pointer gap-2"
                            >
                              <div className="flex items-center gap-2.5 min-w-0 flex-1">
                                <div className="relative w-8 h-8 rounded-lg overflow-hidden shrink-0 bg-zinc-100 dark:bg-zinc-800 border border-zinc-200/60 dark:border-zinc-700">
                                  <ImageWithFallback
                                    src={getServiceThumbnail(item)}
                                    fallbackSrc="/images/fallback-placeholder.svg"
                                    alt={item.name}
                                    fill
                                    sizes="32px"
                                    className="object-cover w-full h-full"
                                  />
                                </div>
                                <div className="min-w-0 flex-1">
                                  <p className="text-xs font-bold text-zinc-800 dark:text-zinc-200 truncate group-hover:text-brand-600 dark:group-hover:text-brand-400 transition-colors">
                                    {item.name}
                                  </p>
                                  <span className="text-[10px] text-zinc-400 font-medium">
                                    {item.category_name || (isAr ? 'خدمة مميزة' : 'Service')}
                                  </span>
                                </div>
                              </div>

                              <div className="shrink-0 text-end">
                                <div className="text-[10px] text-zinc-400">{isAr ? 'يبدأ من' : 'From'}</div>
                                <PriceDisplay
                                  amount={item.discount_price ?? item.price}
                                  className="text-xs font-extrabold text-zinc-900 dark:text-white"
                                  iconClassName="w-2.5 h-2.5 mr-0.5 inline-block text-brand-500"
                                />
                              </div>
                            </button>
                          ))}
                        </div>
                      </>
                    )}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* ── Book CTA Button ── */}
          <button
            type="submit"
            className="h-11 px-6 bg-zinc-950 hover:bg-zinc-850 dark:bg-white dark:text-zinc-950 dark:hover:bg-zinc-100 text-white text-sm font-bold rounded-xl md:rounded-full transition-all flex items-center justify-center gap-1.5 shrink-0 cursor-pointer shadow-sm"
          >
            <span>{isAr ? 'احجز الآن' : 'Book'}</span>
            <span className="text-xs rtl:rotate-180">→</span>
          </button>
        </form>
      </div>
    </>
  );
}

export default PremiumBookingBar;
