'use client'

import { useState, useEffect, useRef } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { newsArticlesApi, NewsArticle } from '@/lib/api'
import { normalizeImageUrl } from '@/lib/media'

// Helper function to format relative time
const getRelativeTime = (dateString: string | undefined) => {
  if (!dateString) return 'Recently'
  const date = new Date(dateString)
  const now = new Date()
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
  
  if (diffInSeconds < 60) return 'Just now'
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`
  if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)} days ago`
  return `${Math.floor(diffInSeconds / 604800)} weeks ago`
}

export default function ArticleCarousel() {
  const [articles, setArticles] = useState<NewsArticle[]>([])
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isLoading, setIsLoading] = useState(true)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    const fetchFeaturedArticles = async () => {
      try {
        // First try to get featured articles
        const featured = await newsArticlesApi.getFeatured(6)
        
        // If no featured articles, fall back to regular published articles
        if (featured.length === 0) {
          const result = await newsArticlesApi.getAll({ limit: 6 })
          setArticles(result.data)
        } else {
          setArticles(featured)
        }
      } catch (error) {
        console.error('Error fetching articles:', error)
        // Try to get regular articles as fallback
        try {
          const result = await newsArticlesApi.getAll({ limit: 6 })
          setArticles(result.data)
        } catch (fallbackError) {
          console.error('Error fetching fallback articles:', fallbackError)
          setArticles([])
        }
      } finally {
        setIsLoading(false)
      }
    }

    fetchFeaturedArticles()
  }, [])

  const goToPrevious = () => {
    if (articles.length === 0) return
    setCurrentIndex((prevIndex) => 
      prevIndex === 0 ? articles.length - 1 : prevIndex - 1
    )
  }

  const goToNext = () => {
    if (articles.length === 0) return
    setCurrentIndex((prevIndex) => 
      prevIndex === articles.length - 1 ? 0 : prevIndex + 1
    )
  }

  // Auto-play functionality
  useEffect(() => {
    if (articles.length === 0) return

    intervalRef.current = setInterval(() => {
      setCurrentIndex((prevIndex) => 
        prevIndex === articles.length - 1 ? 0 : prevIndex + 1
      )
    }, 8000) // 8 seconds per slide

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

  // Reset interval when manually navigating
  const resetInterval = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current)
    }
    if (articles.length > 0) {
    intervalRef.current = setInterval(() => {
      setCurrentIndex((prevIndex) => 
        prevIndex === articles.length - 1 ? 0 : prevIndex + 1
      )
    }, 8000)
    }
  }

  const handlePrevious = () => {
    goToPrevious()
    resetInterval()
  }

  const handleNext = () => {
    goToNext()
    resetInterval()
  }

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

  if (isLoading) {
    return (
      <section className="py-6 px-4">
        <div className="max-w-6xl mx-auto">
          <div className="flex h-[260px] sm:h-[300px] lg:h-[360px] items-center justify-center">
            <div className="text-white/70">Loading featured articles...</div>
          </div>
        </div>
      </section>
    )
  }

  if (articles.length === 0) {
    // Don't render anything if no articles are available
    return null
  }

  return (
    <section className="py-6 px-4">
      <div className="max-w-6xl mx-auto">
        <div className="relative">
          <div className="flex h-[260px] sm:h-[300px] lg:h-[360px] gap-0">
            {articles.map((article, index) => {
              const isActive = index === currentIndex

              return (
                <Link
                  key={article._id}
                  href={article.link || `/news/${article._id}`}
                  className={`relative group overflow-hidden rounded-3xl border border-white/10 bg-white shadow-xl transition-all duration-500 ease-in-out cursor-pointer ${
                    isActive
                      ? 'flex-[5] ring-2 ring-primary/60 z-20 ml-0'
                      : 'flex-[1] hover:flex-[1.2] z-10 -ml-6 sm:-ml-8'
                  } min-w-[56px] sm:min-w-[72px] first:ml-0 focus:outline-none focus:ring-2 focus:ring-primary`}
                  aria-label={`View article: ${article.title}`}
                >
                  <Image
                    src={normalizeImageUrl(article.imageUrl) || '/news-carousel-default.jpg'}
                    alt={article.title}
                    fill
                    className="object-cover"
                    priority={index === 0}
                    onError={(e) => {
                      // Fallback to default image if image fails to load
                      const target = e.target as HTMLImageElement
                      target.src = '/news-carousel-default.jpg'
                    }}
                  />
                  <div className={`absolute inset-0 transition-opacity ${
                    isActive ? 'bg-black/40' : 'bg-black/50'
                  }`} />

                  {/* Expanded Content */}
                  <div className={`absolute inset-0 flex flex-col justify-end p-5 transition-opacity ${
                    isActive ? 'opacity-100' : 'opacity-0'
                  }`}>
                    <motion.h2
                      key={`${article._id}-title`}
                      initial={{ y: -40, opacity: 0 }}
                      animate={isActive ? { y: 0, opacity: 1 } : { y: -40, opacity: 0 }}
                      transition={{ 
                        duration: 0.6, 
                        ease: 'easeOut',
                        delay: isActive ? 0.5 : 0 // Delay until slide transition completes (500ms)
                      }}
                      className="text-lg md:text-xl font-bold text-white mb-2 leading-tight line-clamp-2"
                    >
                      {article.title}
                    </motion.h2>
                    <motion.p
                      key={`${article._id}-excerpt`}
                      initial={{ y: -30, opacity: 0 }}
                      animate={isActive ? { y: 0, opacity: 1 } : { y: -30, opacity: 0 }}
                      transition={{ 
                        duration: 0.6, 
                        ease: 'easeOut',
                        delay: isActive ? 0.6 : 0 // Slightly after title animation starts
                      }}
                      className="text-sm text-white/90 mb-3 leading-relaxed line-clamp-2"
                    >
                      {article.description}
                    </motion.p>
                    <div className="text-xs text-white/80">
                      Updated {getRelativeTime(article.publishedAt || article.createdAt)}
                    </div>
                  </div>
                </Link>
              )
            })}
              </div>

          {/* Previous Button - Left Side */}
          <button
            onClick={(e) => {
              e.preventDefault()
              e.stopPropagation()
              handlePrevious()
            }}
            className="absolute left-2 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/90 shadow-lg flex items-center justify-center hover:bg-white transition-colors focus:outline-none focus:ring-2 focus:ring-primary z-30"
            aria-label="Previous article"
          >
            <ChevronLeft className="w-5 h-5 text-gray-700" />
          </button>

          {/* Next Button - Right Side */}
          <button
            onClick={(e) => {
              e.preventDefault()
              e.stopPropagation()
              handleNext()
            }}
            className="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/90 shadow-lg flex items-center justify-center hover:bg-white transition-colors focus:outline-none focus:ring-2 focus:ring-primary z-30"
            aria-label="Next article"
          >
            <ChevronRight className="w-5 h-5 text-gray-700" />
          </button>
        </div>

        {/* Progress Dots - Bottom */}
        <div className="flex items-center justify-center gap-2 mt-4">
          {articles.map((_, index) => (
            <button
              key={index}
              onClick={(e) => {
                e.preventDefault()
                e.stopPropagation()
                handleDotClick(index)
              }}
              className={`h-2 rounded-full transition-all ${
                index === currentIndex
                  ? 'bg-primary w-8'
                  : 'bg-gray-300 hover:bg-gray-400 w-2'
              }`}
              aria-label={`Go to article ${index + 1}`}
            />
          ))}
        </div>
      </div>
    </section>
  )
}
