import React, { useState, useEffect, useCallback } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { navigateTo } from "./Router";
import PrimaryCTAButton from "./PrimaryCTAButton";

interface HeroSectionItem {
  id: string;
  headline: string;
  subtext: string;
  background_image_url: string;
  cta_text: string;
  cta_destination: string;
}

interface SlideData {
  id: string;
  title: string;
  backgroundImage: string;
  shortTitle: string;
  ctaText: string;
  route: string;
}

interface HeroSectionProps {
  heroSections: HeroSectionItem[];
  isLoading: boolean;
}

export default function HeroSection({
  heroSections,
  isLoading,
}: HeroSectionProps) {
  const slides: SlideData[] = heroSections.map((item) => ({
    id: item.id,
    title: item.headline,
    backgroundImage: item.background_image_url,
    shortTitle: item.subtext,
    ctaText: item.cta_text,
    route: item.cta_destination,
  }));

  const totalSlides = slides.length;

  const [currentSlide, setCurrentSlide] = useState(0);
  const [isAutoPlaying, setIsAutoPlaying] = useState(true);
  const [progressValues, setProgressValues] = useState<number[]>([]);

  const slideDuration = 5000;

  /* Initialize progress array when slides load */
  useEffect(() => {
    if (totalSlides > 0) {
      setProgressValues(new Array(totalSlides).fill(0));
    }
  }, [totalSlides]);

  /* Auto slide */
  useEffect(() => {
    if (!isAutoPlaying || totalSlides === 0) return;

    const interval = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % totalSlides);
    }, slideDuration);

    return () => clearInterval(interval);
  }, [isAutoPlaying, totalSlides]);

  /* Progress animation */
  useEffect(() => {
    if (!isAutoPlaying || totalSlides === 0) return;

    const interval = setInterval(() => {
      setProgressValues((prev) => {
        const newProgress = [...prev];

        newProgress[currentSlide] = Math.min(
          newProgress[currentSlide] + 100 / (slideDuration / 100),
          100
        );

        if (newProgress[currentSlide] >= 100) {
          newProgress[currentSlide] = 0;

          newProgress.forEach((_, index) => {
            if (index !== currentSlide) newProgress[index] = 0;
          });
        }

        return newProgress;
      });
    }, 100);

    return () => clearInterval(interval);
  }, [currentSlide, isAutoPlaying, totalSlides]);

  /* Reset progress when slide changes */
  useEffect(() => {
    setProgressValues(new Array(totalSlides).fill(0));
  }, [currentSlide, totalSlides]);

  const goToSlide = useCallback(
    (slideIndex: number) => {
      if (slideIndex !== currentSlide) {
        setCurrentSlide(slideIndex);
        setIsAutoPlaying(false);

        setTimeout(() => setIsAutoPlaying(true), 3000);
      }
    },
    [currentSlide]
  );

  const nextSlide = useCallback(() => {
    const next = (currentSlide + 1) % totalSlides;
    goToSlide(next);
  }, [currentSlide, totalSlides, goToSlide]);

  const prevSlide = useCallback(() => {
    const prev = (currentSlide - 1 + totalSlides) % totalSlides;
    goToSlide(prev);
  }, [currentSlide, totalSlides, goToSlide]);

  const handleMouseEnter = () => setIsAutoPlaying(false);
  const handleMouseLeave = () => setIsAutoPlaying(true);

  if (isLoading || slides.length === 0) return null;

  return (
    <section
      className="hero-section"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {/* Background Slides */}
      {slides.map((slide, index) => (
        <div
          key={slide.id}
          className={`hero-slide ${index === currentSlide ? "active" : ""}`}
          style={{
            backgroundImage: `url('${slide.backgroundImage}')`,
          }}
        >
          <div className="hero-overlay" />
        </div>
      ))}

      {/* Hero Content */}
      <div className="hero-content">
        <div className="hero-text-section">
          <h1 className="hero-title" style={{ whiteSpace: "pre-line" }}>
            {slides[currentSlide].title}
          </h1>

          <PrimaryCTAButton
            text={slides[currentSlide].ctaText}
            onClick={() => navigateTo(slides[currentSlide].route)}
            ariaLabel="Learn more about KLC"
          />
        </div>
      </div>

      {/* Bottom Navigation */}
      <div className="hero-navigation">
        <div className="hero-progress-container">
          {slides.map((slide, index) => (
            <div
              key={slide.id}
              className="hero-progress-item"
              onClick={() => goToSlide(index)}
            >
              <div
                className={`hero-progress-segment ${
                  index === currentSlide ? "active" : ""
                }`}
              >
                <div
                  className="hero-progress-fill"
                  style={{
                    width:
                      index === currentSlide
                        ? `${progressValues[index] ?? 0}%`
                        : "0%",
                  }}
                />
              </div>

              <div
                className={`hero-progress-number ${
                  index === currentSlide ? "active" : ""
                }`}
              >
                {String(index + 1).padStart(2, "0")}
              </div>

              <div
                className={`hero-progress-text ${
                  index === currentSlide ? "active" : ""
                }`}
              >
                {slide.shortTitle}
              </div>
            </div>
          ))}
        </div>

        <div className="hero-controls">
          <button
            className="hero-nav-button"
            onClick={prevSlide}
            aria-label="Previous slide"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>

          <button
            className="hero-nav-button"
            onClick={nextSlide}
            aria-label="Next slide"
          >
            <ChevronRight className="w-5 h-5" />
          </button>
        </div>
      </div>
    </section>
  );
}