'use client';

import * as React from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';

interface Article {
  slug: string;
  title: string;
  cardImage: string | null;
  excerpt: string | null;
  category: string | null;
}

interface BlogCarouselProps {
  articles: Article[];
  autoRotateInterval?: number;
}

export function BlogCarousel({ 
  articles, 
  autoRotateInterval = 5000 
}: BlogCarouselProps) {
  const [currentIndex, setCurrentIndex] = React.useState(0);
  const [isPaused, setIsPaused] = React.useState(false);
  const [imageErrors, setImageErrors] = React.useState<Record<number, boolean>>({});
  const intervalRef = React.useRef<NodeJS.Timeout | null>(null);

  // Auto-rotation logic
  React.useEffect(() => {
    if (articles.length <= 1 || isPaused) return;

    intervalRef.current = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % articles.length);
    }, autoRotateInterval);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [articles.length, autoRotateInterval, isPaused]);

  const handleDotClick = (index: number) => {
    setCurrentIndex(index);
  };

  const handleImageError = (index: number) => {
    setImageErrors((prev) => ({ ...prev, [index]: true }));
  };

  if (articles.length === 0) return null;

  const currentArticle = articles[currentIndex];

  return (
    <div 
      className="relative"
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      {/* Carousel Content */}
      <Link 
        href={`/post/${encodeURIComponent(currentArticle.slug)}`}
        className="block group"
      >
        <div className="bg-[#202026] rounded-xl overflow-hidden hover:shadow-[0_0_20px_rgba(230,0,35,0.3)] transition-all duration-300 border border-transparent hover:border-[#E60023]">
          {/* Image Container with Fade Transition */}
          <div className="relative aspect-video overflow-hidden bg-gradient-to-br from-gray-800 to-gray-900">
            {articles.map((article, index) => (
              <div
                key={article.slug}
                className={cn(
                  'absolute inset-0 transition-opacity duration-700 ease-in-out',
                  index === currentIndex ? 'opacity-100 z-10' : 'opacity-0 z-0'
                )}
              >
                {article.cardImage && !imageErrors[index] ? (
                  <Image
                    src={article.cardImage}
                    alt={article.title}
                    fill
                    priority={index === 0}
                    className="object-cover transition-transform duration-300 group-hover:scale-105"
                    sizes="(max-width: 768px) 100vw, (max-width: 1280px) 90vw, 1200px"
                    unoptimized
                    onError={() => handleImageError(index)}
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center">
                    <div className="text-center p-6">
                      <div className="text-6xl mb-2">📰</div>
                      <p className="text-gray-400 text-sm">No Image Available</p>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
          
          {/* Content with Fade Transition */}
          <div className="p-6 md:p-8 relative">
            {articles.map((article, index) => (
              <div
                key={`content-${article.slug}`}
                className={cn(
                  'transition-opacity duration-700 ease-in-out',
                  index === currentIndex ? 'opacity-100' : 'opacity-0 absolute inset-0 p-6 md:p-8 pointer-events-none'
                )}
              >
                {/* Category Badge */}
                {article.category && (
                  <Badge className="mb-3 bg-[#E60023] hover:bg-[#FF2A3D] text-white border-transparent">
                    {article.category}
                  </Badge>
                )}
                
                {/* Title */}
                <h2 className="text-2xl md:text-3xl lg:text-4xl font-bold text-white mb-3 leading-tight group-hover:text-[#E60023] transition-colors">
                  {article.title}
                </h2>
                
                {/* Excerpt */}
                {article.excerpt && (
                  <p className="text-base md:text-lg text-[#B8B8C0] line-clamp-2 leading-[1.8]">
                    {article.excerpt}
                  </p>
                )}
              </div>
            ))}
          </div>
        </div>
      </Link>

      {/* Navigation Dots */}
      {articles.length > 1 && (
        <div className="flex justify-center gap-2 mt-4">
          {articles.map((_, index) => (
            <button
              key={index}
              onClick={() => handleDotClick(index)}
              className={cn(
                'h-2 rounded-full transition-all duration-300',
                index === currentIndex 
                  ? 'w-8 bg-[#E60023]' 
                  : 'w-2 bg-gray-600 hover:bg-gray-500'
              )}
              aria-label={`Go to slide ${index + 1}`}
            />
          ))}
        </div>
      )}
    </div>
  );
}
