"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import Link from "next/link";
import { Search, ArrowRight, ChevronLeft, ChevronRight, Tag, Truck, ShieldCheck } from "lucide-react";

type DbSlide = {
  id: string;
  imageUrl: string;
  title: string | null;
  subtitle: string | null;
  ctaText: string | null;
  ctaLink: string | null;
  isActive: boolean;
  sortOrder: number;
};

// Legacy hardcoded slides kept for fallback
const FALLBACK_SLIDES = [
  {
    id: "1",
    image: "https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?w=1920&q=80",
    tag: "New Arrivals",
    title: "Premium Products",
    highlight: "Delivered Fast",
    description: "Explore our curated collection of top-quality electronics, fashion, and lifestyle products.",
    cta: { label: "Shop Now", href: "/shop" },
    badge: "Free shipping above $150",
  },
  {
    id: "2",
    image: "https://images.unsplash.com/photo-1441986380878-c4248f5b8b5b?w=1920&q=80",
    tag: "Fashion",
    title: "Style That",
    highlight: "Defines You",
    description: "Discover the latest fashion trends and accessories — curated for modern Malaysian lifestyles.",
    cta: { label: "Browse Fashion", href: "/shop" },
    badge: "Up to 40% off",
  },
  {
    id: "3",
    image: "https://images.unsplash.com/photo-1472851294608-062f824d29cc?w=1920&q=80",
    tag: "Electronics",
    title: "Tech That",
    highlight: "Works For You",
    description: "The latest gadgets, wearables, and smart devices — all verified and ready to ship.",
    cta: { label: "Shop Electronics", href: "/shop" },
    badge: "12-month warranty",
  },
];

export default function ShopSlider({ slides: dbSlides }: { slides?: DbSlide[] }) {
  // Convert DB slides to display format, or use fallback
  const slides = dbSlides && dbSlides.length > 0
    ? dbSlides.map(s => ({
        id: s.id,
        image: s.imageUrl,
        tag: "",
        title: s.title ?? "Shop Now",
        highlight: "",
        description: s.subtitle ?? "",
        cta: { label: s.ctaText ?? "Shop Now", href: s.ctaLink ?? "/shop" },
        badge: "",
      }))
    : FALLBACK_SLIDES;

  const [current, setCurrent] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [query, setQuery] = useState("");

  const goTo = useCallback((index: number) => {
    if (isTransitioning) return;
    setIsTransitioning(true);
    setCurrent(index);
    setTimeout(() => setIsTransitioning(false), 600);
  }, [isTransitioning]);

  const next = useCallback(() => goTo((current + 1) % slides.length), [current, goTo]);
  const prev = () => goTo((current - 1 + slides.length) % slides.length);

  useEffect(() => {
    const t = setInterval(next, 5000);
    return () => clearInterval(t);
  }, [next]);

  const slide = slides[current];

  return (
    <div className="relative">
      {/* Slider */}
      <section className="relative h-[420px] md:h-[480px] overflow-hidden bg-navy-900">
        {slides.map((s, i) => (
          <div key={s.id} className="absolute inset-0 transition-opacity duration-700" style={{ opacity: i === current ? 1 : 0 }}>
            <Image src={s.image} alt={s.title} fill priority={i === 0} className="object-cover" sizes="100vw" />
            <div className="absolute inset-0 bg-gradient-to-r from-navy-950/85 via-navy-900/60 to-transparent" />
          </div>
        ))}

        <div className="relative z-10 h-full flex items-center pb-16">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
            <div className="max-w-xl">
              <div className="inline-flex items-center gap-1.5 px-3 py-1 bg-gold-500/20 text-gold-300 text-xs font-semibold rounded-full mb-4 border border-gold-500/30">
                <Tag size={11} /> {slide.tag}
              </div>
              <h1 className="text-3xl md:text-5xl font-bold text-white leading-tight">
                {slide.title}<br /><span className="text-gold-400">{slide.highlight}</span>
              </h1>
              <p className="mt-3 text-sm md:text-base text-white/75 leading-relaxed">{slide.description}</p>
              <div className="mt-5 flex items-center gap-4">
                <Link href={slide.cta.href} className="inline-flex items-center gap-2 px-5 py-2.5 bg-gold-500 text-white font-semibold text-sm rounded-xl hover:bg-gold-400 transition-colors">
                  {slide.cta.label} <ArrowRight size={15} />
                </Link>
                <span className="flex items-center gap-1.5 text-xs text-white/60">
                  <ShieldCheck size={13} className="text-emerald-400" />{slide.badge}
                </span>
              </div>
            </div>
          </div>
        </div>

        <button onClick={prev} className="absolute left-3 top-1/2 -translate-y-1/2 z-20 w-9 h-9 bg-white/10 hover:bg-white/25 border border-white/20 rounded-full flex items-center justify-center text-white backdrop-blur-sm transition-colors"><ChevronLeft size={18} /></button>
        <button onClick={next} className="absolute right-3 top-1/2 -translate-y-1/2 z-20 w-9 h-9 bg-white/10 hover:bg-white/25 border border-white/20 rounded-full flex items-center justify-center text-white backdrop-blur-sm transition-colors"><ChevronRight size={18} /></button>

        <div className="absolute bottom-20 left-1/2 -translate-x-1/2 z-20 flex gap-2">
          {slides.map((_, i) => (
            <button key={i} onClick={() => goTo(i)} className={`transition-all rounded-full ${i === current ? "w-5 h-1.5 bg-gold-400" : "w-1.5 h-1.5 bg-white/40"}`} />
          ))}
        </div>
      </section>

      {/* Floating search bar */}
      <div className="relative z-20 -mt-8 max-w-3xl mx-auto px-4">
        <div className="bg-white rounded-2xl shadow-xl border border-neutral-200 flex items-center gap-2 p-2">
          <div className="relative flex-1">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400" />
            <input
              type="search"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search products, brands, categories..."
              className="w-full pl-10 pr-4 py-2.5 text-sm focus:outline-none text-neutral-800 placeholder-neutral-400"
            />
          </div>
          <div className="hidden sm:block w-px h-6 bg-neutral-200" />
          <select className="hidden sm:block text-sm text-neutral-600 px-2 py-2 focus:outline-none bg-transparent">
            <option>All Categories</option>
            <option>Electronics</option>
            <option>Fashion</option>
            <option>Home & Living</option>
            <option>Sports</option>
            <option>Books</option>
            <option>Beauty</option>
          </select>
          <button className="px-5 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-xl hover:bg-navy-800 transition-colors flex items-center gap-2 shrink-0">
            <Search size={14} /> Search
          </button>
        </div>
        <div className="flex items-center justify-center gap-6 mt-3">
          {[
            { icon: Truck, text: "Free shipping over $150" },
            { icon: ShieldCheck, text: "Secure checkout" },
            { icon: Tag, text: "Best price guarantee" },
          ].map(({ icon: Icon, text }) => (
            <div key={text} className="flex items-center gap-1.5 text-xs text-neutral-500">
              <Icon size={12} className="text-navy-500" /> {text}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
