"use client";

import { useEffect, useCallback, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import useEmblaCarousel from "embla-carousel-react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { HERO_BLUR } from "@/lib/blurPlaceholder";
import { resolveUploadUrl } from "@/lib/uploadUrl";

export interface HeroBanner {
  id: string;
  title: string;
  subtitle?: string;
  description?: string;
  imageDesktop: string;
  imageMobile?: string;
  buttonText?: string;
  buttonUrl?: string;
  priority?: number;
  isActive?: boolean;
}

interface Props {
  banners: HeroBanner[];
  /** Auto-advance interval in ms. 0 = disabled. Default 5000. */
  interval?: number;
}

const FALLBACK_BANNERS: HeroBanner[] = [
  {
    id: "fallback-1",
    title: "Find Your Dream Car",
    subtitle: "India's Smartest Car Marketplace",
    description: "Compare 500+ cars across 30+ brands with real prices, specs & expert insights.",
    imageDesktop: "",
    buttonText: "Explore Cars",
    buttonUrl: "/cars",
  },
];

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";

/** Fire-and-forget banner analytics event — never throws. */
function trackBanner(id: string, event: "view" | "click") {
  // Skip fallback / placeholder banners that have no real DB id
  if (!id || id.startsWith("fallback")) return;
  fetch(`${API_BASE}/api/banners/${id}/${event}`, { method: "POST" }).catch(() => {});
}

export default function HeroBannerSlider({ banners, interval = 5000 }: Props) {
  const slides = banners.length > 0 ? banners : FALLBACK_BANNERS;
  const [current, setCurrent] = useState(0);
  const [isHovered, setIsHovered] = useState(false);

  const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true, duration: 40 });

  const onSelect = useCallback(() => {
    if (!emblaApi) return;
    setCurrent(emblaApi.selectedScrollSnap());
  }, [emblaApi]);

  useEffect(() => {
    if (!emblaApi) return;
    emblaApi.on("select", onSelect);
    return () => { emblaApi.off("select", onSelect); };
  }, [emblaApi, onSelect]);

  // Track view whenever the visible banner changes
  useEffect(() => {
    const banner = slides[current];
    if (banner) trackBanner(banner.id, "view");
  }, [current, slides]);

  // Auto-advance
  useEffect(() => {
    if (!emblaApi || interval <= 0 || isHovered) return;
    const timer = setInterval(() => emblaApi.scrollNext(), interval);
    return () => clearInterval(timer);
  }, [emblaApi, interval, isHovered]);

  // Touch / swipe is natively handled by embla

  const scrollTo = useCallback((idx: number) => emblaApi?.scrollTo(idx), [emblaApi]);
  const prev = useCallback(() => emblaApi?.scrollPrev(), [emblaApi]);
  const next = useCallback(() => emblaApi?.scrollNext(), [emblaApi]);

  return (
    <section
      className="relative w-full overflow-hidden"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      aria-label="Featured banner slider"
    >
      {/* Embla viewport */}
      <div ref={emblaRef} className="overflow-hidden">
        <div className="flex">
          {slides.map((banner, idx) => (
            <Slide
              key={banner.id}
              banner={banner}
              active={idx === current}
              onCtaClick={() => trackBanner(banner.id, "click")}
            />
          ))}
        </div>
      </div>

      {/* Navigation arrows — only when multiple slides */}
      {slides.length > 1 && (
        <>
          <button
            onClick={prev}
            aria-label="Previous banner"
            className="absolute left-3 top-1/2 -translate-y-1/2 z-20 w-9 h-9 md:w-11 md:h-11 bg-black/30 hover:bg-black/50 backdrop-blur-sm rounded-full flex items-center justify-center text-white transition-all hover:scale-110 focus:outline-none focus:ring-2 focus:ring-white/50"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <button
            onClick={next}
            aria-label="Next banner"
            className="absolute right-3 top-1/2 -translate-y-1/2 z-20 w-9 h-9 md:w-11 md:h-11 bg-black/30 hover:bg-black/50 backdrop-blur-sm rounded-full flex items-center justify-center text-white transition-all hover:scale-110 focus:outline-none focus:ring-2 focus:ring-white/50"
          >
            <ChevronRight className="w-5 h-5" />
          </button>
        </>
      )}

      {/* Dot indicators */}
      {slides.length > 1 && (
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-20 flex gap-1.5" role="tablist" aria-label="Banner slides">
          {slides.map((_, idx) => (
            <button
              key={idx}
              role="tab"
              aria-selected={idx === current}
              aria-label={`Go to slide ${idx + 1}`}
              onClick={() => scrollTo(idx)}
              className={cn(
                "rounded-full transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-white/60",
                idx === current
                  ? "w-6 h-2 bg-white"
                  : "w-2 h-2 bg-white/50 hover:bg-white/80"
              )}
            />
          ))}
        </div>
      )}
    </section>
  );
}

// ── Individual slide ──────────────────────────────────────────────────────────

function Slide({ banner, active, onCtaClick }: { banner: HeroBanner; active: boolean; onCtaClick?: () => void }) {
  const hasImage = Boolean(banner.imageDesktop);

  return (
    <div
      className="relative flex-shrink-0 w-full h-[300px] sm:h-[380px] md:h-[460px] lg:h-[520px]"
      aria-hidden={!active}
    >
      {/* Background */}
      {hasImage ? (
        <>
          {/* Mobile image */}
          <Image
            src={resolveUploadUrl(banner.imageMobile || banner.imageDesktop)}
            alt={banner.title}
            fill
            priority={active}
            placeholder="blur"
            blurDataURL={HERO_BLUR}
            quality={80}
            className="object-cover md:hidden"
            sizes="100vw"
          />
          {/* Desktop image */}
          <Image
            src={resolveUploadUrl(banner.imageDesktop)}
            alt={banner.title}
            fill
            priority={active}
            placeholder="blur"
            blurDataURL={HERO_BLUR}
            quality={85}
            className="hidden md:block object-cover"
            sizes="100vw"
          />
          {/* Dark gradient overlay for text legibility */}
          <div className="absolute inset-0 bg-gradient-to-r from-black/65 via-black/35 to-transparent" />
        </>
      ) : (
        /* Fallback gradient when no image set */
        <div className="absolute inset-0 bg-gradient-to-br from-[#0f172a] via-[#172554] to-[#0f766e]">
          <div className="absolute top-0 left-0 w-[400px] h-[400px] bg-cyan-500/20 rounded-full blur-3xl pointer-events-none" />
          <div className="absolute bottom-0 right-0 w-[400px] h-[400px] bg-blue-500/15 rounded-full blur-3xl pointer-events-none" />
        </div>
      )}

      {/* Content */}
      <div className="relative h-full max-w-[1280px] mx-auto px-4 flex flex-col justify-center">
        <div className="max-w-xl">
          {banner.subtitle && (
            <p className="inline-flex items-center gap-2 text-xs md:text-sm font-semibold text-cyan-300 bg-white/10 backdrop-blur-sm border border-white/20 px-3 py-1.5 rounded-full mb-3">
              {banner.subtitle}
            </p>
          )}
          <h2 className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-black text-white leading-tight mb-3">
            {banner.title}
          </h2>
          {banner.description && (
            <p className="text-sm md:text-base text-white/80 mb-5 leading-relaxed max-w-md line-clamp-2">
              {banner.description}
            </p>
          )}
          {banner.buttonText && banner.buttonUrl && (
            <Link
              href={banner.buttonUrl}
              onClick={onCtaClick}
              className="inline-flex items-center gap-2 bg-white text-gray-900 font-bold text-sm px-5 py-2.5 rounded-xl hover:bg-blue-50 transition-all hover:scale-105 active:scale-95 shadow-lg"
            >
              {banner.buttonText}
              <ChevronRight className="w-4 h-4" />
            </Link>
          )}
        </div>
      </div>
    </div>
  );
}
