"use client";

import { ChevronLeft, ChevronRight } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";

interface BlogPost {
  title: string;
  slug: string;
  category: string;
  image: string;
  description: string;
}

interface HeroProps {
  posts: BlogPost[];
}

const AUTOPLAY_INTERVAL = 5000;
const FADE_DURATION = 600;

export function ResourcesHero({ posts }: HeroProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [nextIndex, setNextIndex] = useState<number | null>(null);
  const [isPaused, setIsPaused] = useState(false);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [fadeState, setFadeState] = useState<
    "visible" | "fading-out" | "fading-in"
  >("visible");
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  const transitionTo = useCallback(
    (newIndex: number) => {
      if (isTransitioning || newIndex === currentIndex) return;

      setIsTransitioning(true);
      setNextIndex(newIndex);
      setFadeState("fading-out");

      // After fade out, switch content
      setTimeout(() => {
        setCurrentIndex(newIndex);
        setFadeState("fading-in");

        // After fade in, complete transition
        setTimeout(() => {
          setNextIndex(null);
          setFadeState("visible");
          setIsTransitioning(false);
        }, FADE_DURATION / 2);
      }, FADE_DURATION / 2);
    },
    [currentIndex, isTransitioning]
  );

  const goToPrevious = useCallback(() => {
    const newIndex = currentIndex === 0 ? posts.length - 1 : currentIndex - 1;
    transitionTo(newIndex);
  }, [currentIndex, posts.length, transitionTo]);

  const goToNext = useCallback(() => {
    const newIndex = currentIndex === posts.length - 1 ? 0 : currentIndex + 1;
    transitionTo(newIndex);
  }, [currentIndex, posts.length, transitionTo]);

  // Autoplay with loop
  useEffect(() => {
    if (isPaused || posts.length <= 1 || isTransitioning) return;

    intervalRef.current = setInterval(() => {
      const newIndex = currentIndex === posts.length - 1 ? 0 : currentIndex + 1;
      transitionTo(newIndex);
    }, AUTOPLAY_INTERVAL);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [isPaused, posts.length, currentIndex, isTransitioning, transitionTo]);

  const getSlideIndex = (offset: number) => {
    const index = currentIndex + offset;
    if (index < 0) return posts.length + index;
    if (index >= posts.length) return index - posts.length;
    return index;
  };

  const prevPost = posts[getSlideIndex(-1)];
  const currentPost = posts[currentIndex];
  const nextPost = posts[getSlideIndex(1)];

  if (!currentPost) return null;

  const getOpacityClass = () => {
    switch (fadeState) {
      case "fading-out":
        return "opacity-0 scale-[0.98]";
      case "fading-in":
        return "opacity-100 scale-100";
      default:
        return "opacity-100 scale-100";
    }
  };

  return (
    <section className="relative pt-24 pb-8 lg:pt-32 lg:pb-12 overflow-hidden">
      {/* Carousel Container */}
      <div
        className="relative h-[360px] md:h-[480px] lg:h-[540px] flex items-center justify-center"
        onMouseEnter={() => setIsPaused(true)}
        onMouseLeave={() => setIsPaused(false)}
      >
        {/* Previous Slide (Left) */}
        {prevPost && (
          <div
            role="button"
            tabIndex={0}
            aria-label={`Article précédent : ${prevPost.title}`}
            className="absolute left-0 w-[280px] md:w-[320px] lg:w-[380px] h-[85%] -translate-x-1/2 lg:-translate-x-1/4 opacity-40 scale-[0.85] cursor-pointer z-0 transition-all duration-700 ease-out hover:opacity-60 hover:scale-[0.87] focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2 rounded-2xl"
            onClick={goToPrevious}
            onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goToPrevious(); } }}
          >
            <div className="relative h-full w-full rounded-2xl overflow-hidden shadow-xl" aria-hidden="true">
              <Image
                src={prevPost.image}
                alt={`Aperçu : ${prevPost.title}`}
                fill
                sizes="380px"
                className="object-cover"
              />
              <div className="absolute inset-0 bg-linear-to-t from-black/70 via-black/20 to-transparent" />
              <div className="absolute bottom-0 left-0 right-0 p-4 lg:p-6">
                <span className="text-lg lg:text-xl font-bold text-white line-clamp-2">
                  {prevPost.title}
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Current Slide (Center) */}
        <div className="relative w-full max-w-4xl mx-4 h-full z-10">
          <Link
            href={`/${currentPost.category}/${currentPost.slug}`}
            className="group block h-full w-full"
          >
            <div
              className={`relative h-full w-full rounded-2xl overflow-hidden shadow-2xl transition-all duration-500 ease-out ${getOpacityClass()}`}
            >
              <Image
                src={currentPost.image}
                alt={currentPost.title}
                fill
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 896px"
                className="object-cover transition-transform duration-700 ease-out group-hover:scale-105"
                priority
              />
              <div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/20 to-transparent" />

              {/* Content with fade transition */}
              <div
                className={`absolute bottom-0 left-0 right-0 p-6 md:p-8 lg:p-10 transition-all duration-500 ease-out ${
                  fadeState === "fading-out"
                    ? "opacity-0 translate-y-4"
                    : "opacity-100 translate-y-0"
                }`}
              >
                <span className="inline-block px-3 py-1 mb-3 text-xs font-bold text-white bg-orange-500/80 rounded-full uppercase tracking-wide">
                  {currentPost.category}
                </span>
                <h2 className="text-2xl md:text-3xl lg:text-4xl font-bold text-white mb-2 leading-tight">
                  {currentPost.title}
                </h2>
                <p className="text-sm md:text-base text-gray-200 max-w-2xl line-clamp-2 hidden md:block">
                  {currentPost.description}
                </p>
              </div>
            </div>
          </Link>

          {/* Navigation Buttons */}
          <button
            onClick={goToPrevious}
            disabled={isTransitioning}
            className="absolute left-4 top-1/2 -translate-y-1/2 z-20 flex h-10 w-10 items-center justify-center rounded-xl bg-white/90 backdrop-blur-sm text-gray-800 shadow-lg transition-all duration-300 hover:bg-orange-600 hover:text-white hover:scale-110 focus:outline-none focus:ring-2 focus:ring-orange-500 disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label="Article précédent"
          >
            <ChevronLeft className="h-5 w-5" />
          </button>
          <button
            onClick={goToNext}
            disabled={isTransitioning}
            className="absolute right-4 top-1/2 -translate-y-1/2 z-20 flex h-10 w-10 items-center justify-center rounded-xl bg-white/90 backdrop-blur-sm text-gray-800 shadow-lg transition-all duration-300 hover:bg-orange-600 hover:text-white hover:scale-110 focus:outline-none focus:ring-2 focus:ring-orange-500 disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label="Article suivant"
          >
            <ChevronRight className="h-5 w-5" />
          </button>

          {/* Dots Indicator */}
          <div className="absolute -bottom-2 left-1/2 -translate-x-1/2 z-20 flex gap-1">
            {posts.map((_, index) => (
              <button
                key={index}
                onClick={() => transitionTo(index)}
                disabled={isTransitioning}
                className="relative p-3 group focus:outline-none"
                aria-label={`Aller à l'article ${index + 1}`}
                aria-current={index === currentIndex ? "true" : undefined}
              >
                <span
                  className={`block rounded-full transition-all duration-500 ease-out ${
                    index === currentIndex
                      ? "w-8 h-2 bg-orange-500"
                      : "w-2 h-2 bg-gray-300 group-hover:bg-gray-400"
                  }`}
                />
              </button>
            ))}
          </div>
        </div>

        {/* Next Slide (Right) */}
        {nextPost && (
          <div
            role="button"
            tabIndex={0}
            aria-label={`Article suivant : ${nextPost.title}`}
            className="absolute right-0 w-[280px] md:w-[320px] lg:w-[380px] h-[85%] translate-x-1/2 lg:translate-x-1/4 opacity-40 scale-[0.85] cursor-pointer z-0 transition-all duration-700 ease-out hover:opacity-60 hover:scale-[0.87] focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2 rounded-2xl"
            onClick={goToNext}
            onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goToNext(); } }}
          >
            <div className="relative h-full w-full rounded-2xl overflow-hidden shadow-xl" aria-hidden="true">
              <Image
                src={nextPost.image}
                alt={`Aperçu : ${nextPost.title}`}
                fill
                sizes="380px"
                className="object-cover"
              />
              <div className="absolute inset-0 bg-linear-to-t from-black/70 via-black/20 to-transparent" />
              <div className="absolute bottom-0 left-0 right-0 p-4 lg:p-6">
                <span className="text-lg lg:text-xl font-bold text-white line-clamp-2">
                  {nextPost.title}
                </span>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Title Section */}
      <div className="text-center mt-12 lg:mt-16 px-4">
        <span className="inline-block px-4 py-1.5 mb-4 text-sm font-medium text-orange-700 bg-orange-50 rounded-full">
          Centre de ressources
        </span>
        <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-gray-900 mb-4">
          Tout savoir sur le{" "}
          <span className="text-orange-700">marché de l&apos;énergie</span>
        </h1>
        <p className="text-lg text-gray-600 max-w-2xl mx-auto">
          Guides pratiques, actualités du marché, réglementations et retours
          d&apos;expérience pour optimiser vos contrats énergie.
        </p>
      </div>
    </section>
  );
}
