"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { ChevronLeft, ChevronRight, ArrowRight, Loader2 } from "lucide-react";
import Link from "next/link";
import NewsCard from "@/components/NewsCard";
import { newsService } from "@/lib/api/public/news";
import type { News } from "@/types/news";

const MAX_BERITA_HOME = 6;
const ITEMS_PER_SLIDE = 3;
const AUTO_SLIDE_MS = 5000;

export default function NewsSection() {
  const [news, setNews] = useState<News[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isVisible, setIsVisible] = useState(false);
  const sectionRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    newsService
      .getLatest(MAX_BERITA_HOME)
      .then((res) => setNews(res.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setIsVisible(true); },
      { threshold: 0.1 }
    );
    if (sectionRef.current) observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  const totalSlides = Math.ceil(news.length / ITEMS_PER_SLIDE);

  const nextSlide = useCallback(() => {
    setCurrentIndex((prev) => (prev === totalSlides - 1 ? 0 : prev + 1));
  }, [totalSlides]);

  const prevSlide = useCallback(() => {
    setCurrentIndex((prev) => (prev === 0 ? totalSlides - 1 : prev - 1));
  }, [totalSlides]);

  useEffect(() => {
    if (totalSlides <= 1) return;
    const interval = setInterval(nextSlide, AUTO_SLIDE_MS);
    return () => clearInterval(interval);
  }, [nextSlide, totalSlides]);

  const visibleNews = news.slice(
    currentIndex * ITEMS_PER_SLIDE,
    currentIndex * ITEMS_PER_SLIDE + ITEMS_PER_SLIDE
  );

  return (
    <section
      ref={sectionRef}
      className="py-16 px-4 sm:px-6 md:px-36 bg-gray-50 relative overflow-hidden"
      id="berita"
    >
      <div className="w-full mx-auto">
        <div
          className={`text-center mb-12 md:mb-16 transition-all duration-700 ${isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
            }`}
        >
          <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-main mb-4">
            Berita <span className="text-brand">Terbaru</span>
          </h2>
          <div className="w-24 h-1 bg-brand mx-auto mb-6"></div>
          <p className="text-lg md:text-xl text-sec max-w-3xl mx-auto">
            Informasi terkini tentang kegiatan dan program PTBMMKI
          </p>
        </div>

        {loading ? (
          <div className="flex items-center justify-center h-64 gap-2 text-gray-400">
            <Loader2 className="w-5 h-5 animate-spin" />
            <span>Memuat berita...</span>
          </div>
        ) : news.length === 0 ? (
          <div className="text-center text-gray-400 py-16">
            <p>Belum ada berita tersedia.</p>
          </div>
        ) : (
          <div className="relative px-8 md:px-12 lg:px-16">
            {totalSlides > 1 && (
              <button
                onClick={prevSlide}
                className="cursor-pointer absolute z-50 top-1/2 left-0 transform -translate-y-1/2 bg-white text-gray-800 w-10 h-10 md:w-12 md:h-12 rounded-full flex items-center justify-center hover:bg-brand hover:text-white transition-all duration-300 shadow-lg border border-gray-200"
                aria-label="Previous slide"
              >
                <ChevronLeft className="w-5 h-5 md:w-6 md:h-6" />
              </button>
            )}

            {totalSlides > 1 && (
              <button
                onClick={nextSlide}
                className="cursor-pointer absolute z-50 top-1/2 right-0 transform -translate-y-1/2 bg-white text-gray-800 w-10 h-10 md:w-12 md:h-12 rounded-full flex items-center justify-center hover:bg-brand hover:text-white transition-all duration-300 shadow-lg border border-gray-200"
                aria-label="Next slide"
              >
                <ChevronRight className="w-5 h-5 md:w-6 md:h-6" />
              </button>
            )}

            <div
              className={`transition-all duration-500 ease-in-out ${isVisible ? "opacity-100" : "opacity-0"
                }`}
            >
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
                {visibleNews.map((item, index) => (
                  <div
                    key={item.id}
                    className={`transition-all duration-500 ${isVisible ? "opacity-100" : "opacity-0"
                      }`}
                    style={{ transitionDelay: `${index * 100}ms` }}
                  >
                    <NewsCard item={item} />
                  </div>
                ))}
              </div>
            </div>

            {totalSlides > 1 && (
              <div className="flex justify-center items-center gap-2 mt-8 md:mt-12">
                {Array.from({ length: totalSlides }).map((_, index) => (
                  <button
                    key={index}
                    onClick={() => setCurrentIndex(index)}
                    className={`h-2 md:h-3 rounded-full transition-all duration-300 ${index === currentIndex
                      ? "bg-brand w-8 md:w-10 scale-110"
                      : "bg-gray-300 hover:bg-gray-400 w-2 md:w-3 hover:scale-110"
                      }`}
                    aria-label={`Go to slide ${index + 1}`}
                  />
                ))}
              </div>
            )}
          </div>
        )}

        {!loading && news.length > 0 && (
          <div
            className={`text-center mt-8 transition-all duration-700 delay-300 ${isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
              }`}
          >
            <div className="inline-flex items-center gap-2 bg-white border border-gray-200 rounded-full px-6 py-3 shadow-md">
              <p className="text-sm md:text-base text-sec">
                Menampilkan{" "}
                <span className="font-bold text-brand">{visibleNews.length}</span> dari{" "}
                <span className="font-bold text-brand">{news.length}</span> berita terbaru
              </p>
            </div>
          </div>
        )}

        <div
          className={`text-center mt-12 transition-all duration-700 delay-200 ${isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
            }`}
        >
          <Link
            href="/berita"
            className="inline-flex items-center gap-3 bg-brand text-white px-8 py-4 rounded-full text-lg font-semibold hover:bg-[#E67817] hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-xl group"
          >
            <span>Lihat Semua Berita</span>
            <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform duration-300" />
          </Link>
        </div>
      </div>
    </section>
  );
}