"use client"

import { useState, useEffect } from "react"
import { motion } from "framer-motion"
import { ArrowRight, Clock, Play, Images } from "lucide-react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { useLocale } from 'next-intl'
import SarLoader from "./sar-loader"

interface Actualite {
  id: number
  title: string
  content: string
  date: string
  image?: string | null
  linkedin_url?: string
  linkedin_media_type?: 'IMAGE' | 'MULTI_PHOTO' | 'VIDEO' | null
  linkedin_media_images?: string[]
  linkedin_video_url?: string
  linkedin_video_thumbnail?: string
}

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'

// Fonction pour tronquer le contenu en résumé
const truncateContent = (content: string, maxLength: number = 150): string => {
  if (content.length <= maxLength) return content
  return content.substring(0, maxLength).trim() + '...'
}

const AUTO_PLAY_INTERVAL = 4000 // Intervalle en ms (4 secondes), modifiable

export default function NewsSection() {
  const locale = useLocale()
  const [featuredIndex, setFeaturedIndex] = useState(0)
  const [isMobile, setIsMobile] = useState(false)
  const [actualites, setActualites] = useState<Actualite[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [gridStyle, setGridStyle] = useState<React.CSSProperties>({})
  const [isPaused, setIsPaused] = useState(false)
  const [autoPlayKey, setAutoPlayKey] = useState(0)

  // Récupérer les actualités depuis l'API
  useEffect(() => {
    const fetchActualites = async () => {
      try {
        setLoading(true)
        setError(null)
        const response = await fetch(`${API_URL}/api/actualites/?locale=${locale}`, {
          signal: AbortSignal.timeout(5000),
        })

        if (!response.ok) {
          throw new Error('Erreur lors de la récupération des actualités')
        }

        const data = await response.json()
        const fetchedActualites = data.results || data
        setActualites(fetchedActualites)

        if (fetchedActualites.length > 0 && featuredIndex >= fetchedActualites.length) {
          setFeaturedIndex(0)
        }
      } catch {
        setError(null)
        setActualites([])
      } finally {
        setLoading(false)
      }
    }

    fetchActualites()
  }, [locale])

  // Détecter si on est en mode mobile et ajuster le grid
  useEffect(() => {
    const checkMobile = () => {
      const isMobileView = window.innerWidth < 1024
      setIsMobile(isMobileView)

      if (!isMobileView) {
        setGridStyle({
          gridTemplateColumns: 'calc(66.666% - 100px) calc(33.333% + 100px)'
        })
      } else {
        setGridStyle({
          gridTemplateColumns: '1fr'
        })
      }
    }
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  // Auto-play : cycle automatique de l'article mis en avant
  useEffect(() => {
    if (actualites.length <= 1 || isPaused) return

    const interval = setInterval(() => {
      setFeaturedIndex(prev => (prev + 1) % actualites.length)
    }, AUTO_PLAY_INTERVAL)

    return () => clearInterval(interval)
  }, [actualites.length, isPaused, autoPlayKey])

  // Clic manuel : change l'article et réinitialise le timer
  const handleNewsClick = (index: number) => {
    setFeaturedIndex(index)
    setAutoPlayKey(prev => prev + 1)
  }

  // Transformer les actualités en format news pour le composant
  const news = actualites.map((actualite) => {
    let imageUrl = actualite.image || "/media/generique.jpg"

    if (actualite.linkedin_media_type === 'MULTI_PHOTO' && actualite.linkedin_media_images && actualite.linkedin_media_images.length > 0) {
      imageUrl = actualite.linkedin_media_images[0]
    } else if (actualite.linkedin_media_type === 'VIDEO' && actualite.linkedin_video_thumbnail) {
      imageUrl = actualite.linkedin_video_thumbnail
    }

    return {
      id: actualite.id,
      title: actualite.title,
      summary: truncateContent(actualite.content),
      date: actualite.date,
      image: imageUrl,
      linkedin_media_type: actualite.linkedin_media_type,
      linkedin_media_images: actualite.linkedin_media_images,
      linkedin_video_url: actualite.linkedin_video_url,
      linkedin_url: actualite.linkedin_url,
    }
  })

  const featuredNews = news[featuredIndex] || null
  const otherNews = news.filter((_, index) => index !== featuredIndex)

  if (loading) {
    return (
      <SarLoader />
    )
  }

  if (error || news.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 text-lg">
          {error || "Aucune actualité disponible"}
        </p>
      </div>
    )
  }

  return (
    <div
      className="grid grid-cols-1 gap-4 sm:gap-6"
      style={gridStyle}
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      {featuredNews && (
        <div className="order-2 lg:order-1 flex flex-col gap-3">
          <motion.div
            key={featuredIndex}
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5 }}
          >
            <Link href={`/${locale}/medias#actualite`}>
              <div className="relative h-[252px] sm:h-[352px] md:h-[452px] lg:h-[524px] rounded-xl sm:rounded-2xl overflow-hidden group cursor-pointer">
                {/* Background Image */}
                <img
                  src={featuredNews.image || "/media/generique.jpg"}
                  alt={featuredNews.title}
                  className="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement
                    target.src = "/media/generique.jpg"
                  }}
                />

                {/* Badge vidéo ou multiPhoto */}
                {featuredNews.linkedin_media_type === 'VIDEO' && (
                  <div className="absolute top-4 left-4 bg-accent text-white px-3 py-1 rounded-full text-xs font-semibold flex items-center gap-2 z-10">
                    <Play size={14} fill="currentColor" />
                    Vidéo
                  </div>
                )}
                {featuredNews.linkedin_media_type === 'MULTI_PHOTO' && featuredNews.linkedin_media_images && featuredNews.linkedin_media_images.length > 1 && (
                  <div className="absolute top-4 left-4 bg-white/90 text-gray-900 px-3 py-1 rounded-full text-xs font-semibold flex items-center gap-2 z-10">
                    <Images size={14} />
                    {featuredNews.linkedin_media_images.length} images
                  </div>
                )}

                {/* Content glassmorphism */}
                <div className="absolute inset-0 flex flex-col justify-end p-4 sm:p-6 md:p-8">
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2, duration: 0.5 }}
                    className="relative backdrop-blur-md bg-black/40 rounded-xl sm:rounded-2xl p-4 sm:p-6 md:p-8 border border-white/10 shadow-2xl"
                  >
                    <motion.h3
                      initial={{ y: 20, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      transition={{ delay: 0.3 }}
                      className="text-xl sm:text-2xl md:text-3xl lg:text-4xl font-bold text-white mb-2 sm:mb-3 md:mb-4"
                    >
                      {featuredNews.title}
                    </motion.h3>

                    <motion.p
                      initial={{ y: 20, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      transition={{ delay: 0.4 }}
                      className="text-sm sm:text-base md:text-lg text-white/95 mb-4 sm:mb-5 md:mb-6 line-clamp-2 sm:line-clamp-3"
                    >
                      {featuredNews.summary}
                    </motion.p>

                    <motion.div
                      initial={{ y: 20, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      transition={{ delay: 0.5 }}
                      className="flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-6"
                    >
                      <span className="text-white/90 text-xs sm:text-sm flex items-center gap-2">
                        <Clock size={14} />
                        {featuredNews.date}
                      </span>
                      <Button variant="secondary" size="sm" className="group/btn hover:bg-white hover:text-primary transition-all text-xs sm:text-sm">
                        Voir plus
                        <ArrowRight className="ml-2 group-hover/btn:translate-x-1 transition-transform" size={16} />
                      </Button>
                    </motion.div>
                  </motion.div>
                </div>
              </div>
            </Link>
          </motion.div>

          {/* Indicateurs de progression (points) */}
          {news.length > 1 && (
            <div className="flex items-center justify-center gap-2">
              {news.map((_, idx) => (
                <button
                  key={idx}
                  type="button"
                  onClick={() => handleNewsClick(idx)}
                  aria-label={`Actualité ${idx + 1}`}
                  className={`rounded-full transition-all duration-300 ${
                    idx === featuredIndex
                      ? 'w-6 h-2 bg-primary'
                      : 'w-2 h-2 bg-gray-300 hover:bg-gray-400'
                  }`}
                />
              ))}
            </div>
          )}
        </div>
      )}

      <div className="relative order-1 lg:order-2">
        <div className="bg-white overflow-hidden h-[252px] sm:h-[352px] md:h-[452px] lg:h-[524px] overflow-x-auto lg:overflow-y-scroll pb-4" style={{ scrollbarWidth: 'thin', scrollbarColor: '#cbd5e1 #f1f5f9' }}>
          {isMobile ? (
            <div className="flex flex-row p-4 space-x-4">
              {otherNews.map((item, index) => (
                <motion.div
                  key={`mobile-${item.title}-${index}`}
                  initial={{ opacity: 0, scale: 0.9, x: -20 }}
                  animate={{ opacity: 1, scale: 1, x: 0 }}
                  transition={{
                    duration: 0.4,
                    ease: [0.34, 1.56, 0.64, 1],
                    delay: index * 0.06
                  }}
                  whileHover={{
                    scale: 1.02,
                    x: -4,
                    transition: { duration: 0.2 }
                  }}
                  onClick={() => handleNewsClick(news.indexOf(item))}
                  className="relative h-[63px] sm:h-[88px] md:h-[113px] w-[280px] sm:w-[320px] lg:w-full lg:h-[131px] rounded-lg overflow-hidden group cursor-pointer flex-shrink-0"
                >
                  <div className="relative z-10 h-full flex items-center gap-3 p-2 sm:p-3">
                    <div className="relative flex-shrink-0 w-[112px] sm:w-[156px] md:w-[201px] lg:w-[168px] h-full rounded-lg overflow-hidden">
                      <Image
                        src={item.image || "/media/generique.jpg"}
                        alt={item.title}
                        fill
                        className="object-cover group-hover:scale-110 transition-transform duration-300"
                        sizes="(max-width: 640px) 112px, (max-width: 768px) 156px, (max-width: 1024px) 201px, 168px"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement
                          target.src = "/media/generique.jpg"
                        }}
                      />
                    </div>

                    <div className="flex-1 flex flex-col justify-center min-w-0 pr-2">
                      <motion.h4
                        className="text-xs sm:text-sm font-semibold text-gray-900 mb-1 line-clamp-2 group-hover:text-[#E52621] transition-colors duration-300"
                        whileHover={{ x: 2 }}
                        transition={{ type: "spring", stiffness: 400, damping: 17 }}
                      >
                        {item.title}
                      </motion.h4>

                      <div className="flex items-center gap-1.5 text-gray-500 text-[10px] sm:text-xs">
                        <Clock size={10} />
                        <span>{item.date}</span>
                      </div>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          ) : (
            <div className="flex lg:flex-col flex-row lg:space-y-0 space-x-4 lg:space-x-0 pb-2">
              {otherNews.map((item, index) => (
                <motion.div
                  key={item.title}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{
                    duration: 0.4,
                    delay: index * 0.05
                  }}
                  whileHover={{
                    scale: 1.01,
                    y: -2,
                    transition: { duration: 0.2 }
                  }}
                  onClick={() => handleNewsClick(news.indexOf(item))}
                  className="relative h-[63px] sm:h-[88px] md:h-[113px] w-[280px] sm:w-[320px] lg:w-full lg:h-[131px] group cursor-pointer flex-shrink-0 hover:bg-gray-50 transition-colors duration-200"
                >
                  <div className="relative z-10 h-full flex items-center gap-3 p-3 sm:p-4">
                    <div className="relative flex-shrink-0 w-[112px] sm:w-[156px] md:w-[201px] lg:w-[168px] h-full rounded-lg overflow-hidden">
                      <Image
                        src={item.image || "/media/generique.jpg"}
                        alt={item.title}
                        fill
                        className="object-cover group-hover:scale-110 transition-transform duration-300"
                        sizes="(max-width: 640px) 112px, (max-width: 768px) 156px, (max-width: 1024px) 201px, 168px"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement
                          target.src = "/media/generique.jpg"
                        }}
                      />
                    </div>

                    <div className="flex-1 flex flex-col justify-center min-w-0 pr-2">
                      <motion.h4
                        className="text-xs sm:text-sm font-semibold text-gray-900 mb-1 line-clamp-2 group-hover:text-[#E52621] transition-colors duration-300"
                        whileHover={{ x: 2 }}
                        transition={{ type: "spring", stiffness: 400, damping: 17 }}
                      >
                        {item.title}
                      </motion.h4>

                      <div className="flex items-center gap-1.5 text-gray-500 text-[10px] sm:text-xs">
                        <Clock size={10} />
                        <span>{item.date}</span>
                      </div>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
