"use client";

import React, {
  useState,
  useEffect,
  useCallback,
  useRef,
} from "react";
import Image from "next/image";
import { ChevronLeft, ChevronRight } from "lucide-react";

const AUTO_SLIDE_INTERVAL = 4000;

type SliderImage = {
  file_url: string;
};

export default function Hero(): JSX.Element {
  const [images, setImages] = useState<string[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const touchStartX = useRef<number | null>(null);

  const totalSlides = images.length;

  /** Fetch slider images */
  const fetchSliderImages = async () => {
    try {
      const res = await fetch("/api/slider", {
        cache: "no-store",
      });

      if (!res.ok) throw new Error("Failed to fetch sliders");

      const data = await res.json();

      const imageUrls =
        data?.slider?.attachments?.map(
          (img: SliderImage) => img.file_url
        ) || [];

      setImages(imageUrls);
    } catch (error) {
      console.error("Slider fetch error:", error);
    }
  };

  useEffect(() => {
    fetchSliderImages();
  }, []);

  const goToPrevSlide = useCallback(() => {
    if (!totalSlides) return;
    setCurrentIndex((prev) =>
      prev === 0 ? totalSlides - 1 : prev - 1
    );
  }, [totalSlides]);

  const goToNextSlide = useCallback(() => {
    if (!totalSlides) return;
    setCurrentIndex((prev) => (prev + 1) % totalSlides);
  }, [totalSlides]);

  useEffect(() => {
    if (!totalSlides) return;
    const interval = setInterval(goToNextSlide, AUTO_SLIDE_INTERVAL);
    return () => clearInterval(interval);
  }, [goToNextSlide, totalSlides]);

  /** Swipe handlers */
  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX;
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (!touchStartX.current) return;
    const deltaX =
      touchStartX.current - e.changedTouches[0].clientX;
    if (deltaX > 50) goToNextSlide();
    if (deltaX < -50) goToPrevSlide();
    touchStartX.current = null;
  };

  if (!images.length) {
    return (
      <div className="h-[45vh] rounded-3xl bg-gray-200 animate-pulse" />
    );
  }

  return (
    <section
      className="relative w-full overflow-hidden rounded-xl md:rounded-xl shadow-xl md:shadow-xl"
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      {/* Slides */}
      <div className="relative h-[26vh] min-h-[250px] w-[98%] lg:w-full mx-auto sm:h-[32vh] md:h-[40vh] lg:h-[50vh]">
        {images && images.map((src, index) => (
          <div
            key={index}
            className={`absolute inset-0 transition-all duration-1000 ease-in-out
              ${
                index === currentIndex
                  ? "opacity-100 scale-100 z-10"
                  : "opacity-0 scale-105 z-0"
              }`}
          >
            <Image
              src={src}
              alt={`Hero slide ${index + 1}`}
              fill
              priority={index === currentIndex}
              sizes="100vw"
              className="object-cover"
            />

            {/* Overlay */}
            <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/30 to-transparent" />

            {/* Text */}
            <div className="absolute bottom-6 sm:bottom-10 left-4 sm:left-8 md:left-14 max-w-xl text-white">
              <h1 className="text-2xl sm:text-3xl md:text-5xl font-extrabold drop-shadow-lg">
                Elevate Your Shopping Experience
              </h1>
              <p className="mt-2 sm:mt-4 text-sm sm:text-base md:text-lg text-gray-200">
                Premium products curated just for you.
              </p>
            </div>
          </div>
        ))}
      </div>

      {/* Navigation */}
      <button
        onClick={goToPrevSlide}
        className="absolute left-4 top-1/2 -translate-y-1/2 z-20 hidden sm:flex h-10 w-10 md:h-12 md:w-12 items-center justify-center rounded-full bg-white/20 backdrop-blur-md hover:bg-white/30 transition"
      >
        <ChevronLeft className="text-white" />
      </button>

      <button
        onClick={goToNextSlide}
        className="absolute right-4 top-1/2 -translate-y-1/2 z-20 hidden sm:flex h-10 w-10 md:h-12 md:w-12 items-center justify-center rounded-full bg-white/20 backdrop-blur-md hover:bg-white/30 transition"
      >
        <ChevronRight className="text-white" />
      </button>

      {/* Indicators */}
      <div className="absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 gap-2">
        {images.map((_, index) => (
          <button
            key={index}
            onClick={() => setCurrentIndex(index)}
            className={`rounded-full transition-all
              ${
                index === currentIndex
                  ? "w-8 h-2 bg-white"
                  : "w-2 h-2 bg-white/50"
              }`}
          />
        ))}
      </div>
    </section>
  );
}
