"use client";

import Image from "next/image";
import { useCallback, useEffect, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronLeft, ChevronRight } from "lucide-react";
import SearchBar from "../search-bar";
import { useUIStore } from "@/store/uiStore";

type Slide = {
  id: number;
  type: "image" | "video";
  src: string;
  alt: string | null;
  content: {
    title: string | null;
    description: string | null;
    buttonText: string | null;
  };
  order: number;
  active: boolean;
};

const Hero = () => {
  const isSearchVisible = useUIStore((state) => state.isSearchVisible);
  const [currentSlide, setCurrentSlide] = useState(0);
  const [slides, setSlides] = useState<Slide[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const fetchSlides = async () => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_URL}/api/slides`,
        );
        if (!response.ok) {
          throw new Error("Failed to fetch slides");
        }
        const data = await response.json();
        // Filter only active slides and sort by order
        const activeSlides = data
          .filter((slide: Slide) => slide.active)
          .sort((a: Slide, b: Slide) => a.order - b.order);
        setSlides(activeSlides);
      } catch (err) {
        setError(err instanceof Error ? err.message : "An error occurred");
        console.error("Error fetching slides:", err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchSlides();
  }, []);

  const goToNextSlide = useCallback(() => {
    if (slides.length > 0) {
      setCurrentSlide((prev) => (prev + 1) % slides.length);
    }
  }, [slides]);

  const goToPreviousSlide = useCallback(() => {
    if (slides.length > 0) {
      setCurrentSlide((prev) => (prev - 1 + slides.length) % slides.length);
    }
  }, [slides]);

  useEffect(() => {
    if (slides.length === 0) return;

    let timer: NodeJS.Timeout;

    const handleSlideChange = () => {
      const slide = slides[currentSlide];
      if (slide.type === "video" && videoRef.current) {
        videoRef.current.currentTime = 0;
        videoRef.current.play().catch((error) => {
          console.error("Video playback failed:", error);
          goToNextSlide();
        });
      } else {
        timer = setTimeout(goToNextSlide, 8000);
      }
    };

    handleSlideChange();

    if (slides[currentSlide].type === "video" && videoRef.current) {
      const video = videoRef.current;
      const handleVideoEnd = () => goToNextSlide();
      video.addEventListener("ended", handleVideoEnd);
      return () => {
        if (video) {
          video.removeEventListener("ended", handleVideoEnd);
          video.pause();
        }
        clearTimeout(timer);
      };
    }

    return () => clearTimeout(timer);
  }, [currentSlide, slides, goToNextSlide]);

  if (isLoading) {
    return (
      <div className="w-full px-4 pb-8 md:px-8 md:pb-12 relative">
        <div className="relative h-[40vh] sm:h-[60vh] md:h-[80vh] overflow-hidden rounded-b-lg max-w-7xl mx-auto bg-gray-200 flex items-center justify-center">
          <div className="animate-pulse text-gray-500">Loading slides...</div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="w-full px-4 pb-8 md:px-8 md:pb-12 relative">
        <div className="relative h-[40vh] sm:h-[60vh] md:h-[80vh] overflow-hidden rounded-b-lg max-w-7xl mx-auto bg-gray-200 flex items-center justify-center">
          <div className="text-red-500">Error: {error}</div>
        </div>
      </div>
    );
  }

  if (slides.length === 0) {
    return (
      <div className="w-full px-4 pb-8 md:px-8 md:pb-12 relative">
        <div className="relative h-[40vh] sm:h-[60vh] md:h-[80vh] overflow-hidden rounded-b-lg max-w-7xl mx-auto bg-gray-200 flex items-center justify-center">
          <div className="text-gray-500">No slides available</div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full px-4 pb-8 md:px-8 md:pb-12 relative">
      {isSearchVisible && (
        <div className="absolute inset-0 flex items-center justify-center z-30 px-4">
          <div className="w-full">
            <div className="max-w-4xl mx-auto">
              <SearchBar
                variant="large"
                placeholder="Search for product name, description, or category..."
              />
            </div>
          </div>
        </div>
      )}
      <section className="relative h-[40vh] sm:h-[60vh] md:h-[80vh] overflow-hidden group rounded-b-lg max-w-7xl mx-auto bg-gray-800">
        <AnimatePresence mode="wait">
          {slides[currentSlide].type === "image" ? (
            <motion.div
              key={`image-${slides[currentSlide].id}`}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.7 }}
              className="absolute inset-0"
            >
              <Image
                src={`${process.env.NEXT_PUBLIC_API_URL}${slides[currentSlide].src}`}
                alt={slides[currentSlide].alt || "Slide image"}
                fill
                className="object-cover"
                priority
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 100vw"
              />
            </motion.div>
          ) : (
            <motion.div
              key={`video-${slides[currentSlide].id}`}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.7 }}
              className="absolute inset-0"
            >
              <video
                ref={videoRef}
                className="h-full w-full object-cover"
                muted
                playsInline
                autoPlay
              >
                <source src={slides[currentSlide].src} type="video/mp4" />
              </video>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Navigation Buttons */}
        <button
          onClick={goToPreviousSlide}
          className="absolute left-4 top-1/2 -translate-y-1/2 z-20 p-2 rounded-full bg-black/30 text-white opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/50"
          aria-label="Previous slide"
        >
          <ChevronLeft className="w-6 h-6" />
        </button>
        <button
          onClick={goToNextSlide}
          className="absolute right-4 top-1/2 -translate-y-1/2 z-20 p-2 rounded-full bg-black/30 text-white opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/50"
          aria-label="Next slide"
        >
          <ChevronRight className="w-6 h-6" />
        </button>

        {/* Slide Indicators */}
        <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex gap-2">
          {slides.map((slide, index) => (
            <button
              key={slide.id}
              onClick={() => setCurrentSlide(index)}
              className={`w-2 h-2 rounded-full transition-all duration-300 ${
                currentSlide === index
                  ? "bg-white w-6"
                  : "bg-white/50 hover:bg-white/80"
              }`}
              aria-label={`Go to slide ${index + 1}`}
            />
          ))}
        </div>
      </section>
    </div>
  );
};

export default Hero;
