"use client"

import { motion } from "framer-motion"
import { useInView } from "react-intersection-observer"
import { useTranslations, useLocale } from 'next-intl'
import { Card, CardContent } from "@/components/ui/card"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import SectionLabel from "@/components/section-label"
import SarLoader from "@/components/sar-loader"
import { Heart, Users, GraduationCap, Leaf, Building2, Calendar, Play, MapPin, Sparkles, ArrowRight, ExternalLink, ChevronLeft, ChevronRight } from "lucide-react"
import Image from "next/image"
import { useState, useEffect } from "react"
import { ACTUALITES_LIST, type SocialAction } from "@/lib/actualites-data"

function mapApiToSocialAction(item: {
  id: number
  title: string
  title_en?: string | null
  content: string
  content_en?: string | null
  date: string
  date_iso?: string
  image?: string | null
  linkedin_url?: string | null
}): SocialAction {
  // Gérer les URLs d'images du backend Laravel
  let imageUrl = item.image || '/media/generique.jpg'
  
  // Si l'image vient du backend Laravel (pas une URL complète)
  if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
    const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://10.113.245.13:8000'
    imageUrl = `${API_URL}/${imageUrl}`
  }
  
  // Si c'est une URL du backend mais relative avec /
  if (imageUrl && imageUrl.startsWith('/media/') && !imageUrl.includes('linkedin')) {
    // C'est probablement du backend Laravel, mais on garde tel quel
    // car le backend a déjà géré le chemin
  }
  
  return {
    id: String(item.id),
    title: item.title,
    titleEn: item.title_en || item.title,
    description: item.content,
    descriptionEn: item.content_en || item.content,
    date: item.date_iso || item.date,
    category: 'communautaire',
    image: imageUrl,
    linkedInUrl: item.linkedin_url || undefined,
  }
}

export interface SocialActionsPageProps {
  /** Étiquette de section (ex. "Actualités" sur /actualite) */
  sectionLabel?: string
  /** Masquer les tags de catégorie sur les cartes */
  hideCategoryTags?: boolean
  /** Utiliser les données de l'API (page /actualite). Sinon utilise la liste statique. */
  useApi?: boolean
}

export default function SocialActionsPage({ sectionLabel: sectionLabelOverride, hideCategoryTags = false, useApi = true }: SocialActionsPageProps = {}) {
  const t = useTranslations('rse')
  const tActualite = useTranslations('actualite')
  const locale = useLocale()
  const sectionLabel = sectionLabelOverride ?? t('sectionLabel')
  const isEn = locale === 'en'
  const [ref2, inView2] = useInView({ triggerOnce: true, threshold: 0.1 })
  const [modalLinkedInUrl, setModalLinkedInUrl] = useState<string | null>(null)
  const [selectedAction, setSelectedAction] = useState<SocialAction | null>(null)
  const [hoveredCard, setHoveredCard] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [apiActions, setApiActions] = useState<SocialAction[] | null>(null)
  const [loading, setLoading] = useState(useApi)
  const [isChangingPage, setIsChangingPage] = useState(false)

  useEffect(() => {
    if (!useApi) {
      setLoading(false)
      return
    }
    
    const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://10.113.245.13:8000'
    
    // Appel vers l'API Laravel (base de données)
    fetch(`${API_URL}/api/actualites/?locale=${locale}`)
      .then((res) => res.ok ? res.json() : Promise.reject())
      .then((data: unknown[]) => {
        const list = Array.isArray(data) ? data : []
        setApiActions(list.map((brut) => {
          const item = brut as Record<string, unknown>
          return mapApiToSocialAction({
          id: item.id as number,
          title: (item.title as string) || '',
          title_en: (item.title_en as string) ?? null,
          content: (item.content as string) || '',
          content_en: (item.content_en as string) ?? null,
          date: (item.date as string) || '',
          date_iso: (item.date_iso as string) ?? undefined,
          image: (item.image as string) ?? null,
          linkedin_url: (item.linkedin_url as string) ?? null,
          })
        }))
      })
      .catch((error) => {
        console.error('Erreur chargement actualités depuis Laravel:', error)
        setApiActions(null)
      })
      .finally(() => setLoading(false))
  }, [locale, useApi])

  const ITEMS_PER_PAGE = 6
  const socialActions = (apiActions !== null && apiActions.length > 0) ? apiActions : ACTUALITES_LIST

  const totalPages = Math.max(1, Math.ceil(socialActions.length / ITEMS_PER_PAGE))
  const displayedActions = socialActions.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  )

  // Fonction pour changer de page avec animation
  const handlePageChange = (newPage: number) => {
    if (newPage === currentPage || isChangingPage) return
    
    setIsChangingPage(true)
    
    // Scroll vers le haut avec animation
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
    
    // Attendre un peu avant de changer la page (pour le scroll)
    setTimeout(() => {
      setCurrentPage(newPage)
      setIsChangingPage(false)
    }, 400)
  }

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'education':
        return GraduationCap
      case 'sante':
        return Heart
      case 'environnement':
        return Leaf
      case 'communautaire':
        return Users
      default:
        return Building2
    }
  }

  const getLinkedInEmbedUrl = (postUrl: string): string => {
    console.log('🔗 URL LinkedIn reçue:', postUrl)
    
    // Si l'URL contient déjà urn:li:, extraire le URN complet
    if (postUrl.includes('urn:li:')) {
      // Format: https://www.linkedin.com/feed/update/urn:li:ugcPost:123456
      const urnMatch = postUrl.match(/urn:li:(ugcPost|activity|share):(\d+)/)
      if (urnMatch) {
        const fullUrn = `urn:li:${urnMatch[1]}:${urnMatch[2]}`
        const embedUrl = `https://www.linkedin.com/embed/feed/update/${fullUrn}`
        console.log('✅ URL embed générée:', embedUrl)
        return embedUrl
      }
    }
    
    // Format 1: activity:123456 ou activity-123456
    let match = postUrl.match(/activity[-:](\d+)/)
    if (match) {
      const embedUrl = `https://www.linkedin.com/embed/feed/update/urn:li:activity:${match[1]}`
      console.log('✅ URL embed générée (activity):', embedUrl)
      return embedUrl
    }
    
    // Format 2: ugcPost:123456 ou ugcPost-123456
    match = postUrl.match(/ugcPost[-:](\d+)/)
    if (match) {
      const embedUrl = `https://www.linkedin.com/embed/feed/update/urn:li:ugcPost:${match[1]}`
      console.log('✅ URL embed générée (ugcPost):', embedUrl)
      return embedUrl
    }
    
    // Format 3: share:123456 ou share-123456
    match = postUrl.match(/share[-:](\d+)/)
    if (match) {
      const embedUrl = `https://www.linkedin.com/embed/feed/update/urn:li:share:${match[1]}`
      console.log('✅ URL embed générée (share):', embedUrl)
      return embedUrl
    }
    
    console.warn('⚠️ Format d\'URL LinkedIn non reconnu:', postUrl)
    return postUrl
  }

  const getCategoryColor = (category: string) => {
    switch (category) {
      case 'education':
        return { bg: 'bg-blue-500', gradient: 'from-blue-500 to-blue-600', light: 'bg-blue-50', text: 'text-blue-600', border: 'border-blue-200' }
      case 'sante':
        return { bg: 'bg-red-500', gradient: 'from-red-500 to-red-600', light: 'bg-red-50', text: 'text-red-600', border: 'border-red-200' }
      case 'environnement':
        return { bg: 'bg-green-500', gradient: 'from-green-500 to-green-600', light: 'bg-green-50', text: 'text-green-600', border: 'border-green-200' }
      case 'communautaire':
        return { bg: 'bg-purple-500', gradient: 'from-purple-500 to-purple-600', light: 'bg-purple-50', text: 'text-purple-600', border: 'border-purple-200' }
      default:
        return { bg: 'bg-gray-500', gradient: 'from-gray-500 to-gray-600', light: 'bg-gray-50', text: 'text-gray-600', border: 'border-gray-200' }
    }
  }

  return (
    <main className="pt-20 bg-white min-h-screen">
      <section className="pt-8 sm:pt-12 md:pt-16 pb-12 sm:pb-16 md:pb-20 lg:pb-24 bg-white" ref={ref2}>
        <div className="max-w-[98%] mx-auto px-2 sm:px-4 lg:px-6">
          <div className="max-w-[98%] mx-auto">
            <SectionLabel title={sectionLabel} />
          </div>
        </div>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-4">
          {loading && <SarLoader />}
          {!loading && (
          <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
            {displayedActions.map((action, index) => {
              const Icon = getCategoryIcon(action.category)
              const colors = getCategoryColor(action.category)
              const isHovered = hoveredCard === action.id
              const hasLinkedIn = Boolean(action.linkedInUrl)

              return (
                <motion.div
                  key={action.id}
                  initial={{ opacity: 0, scale: 0.8, y: 50, rotateX: -15 }}
                  whileInView={{ opacity: 1, scale: 1, y: 0, rotateX: 0 }}
                  viewport={{ once: true }}
                  transition={{ duration: 0.7, delay: index * 0.15, type: "spring", stiffness: 100 }}
                  onHoverStart={() => setHoveredCard(action.id)}
                  onHoverEnd={() => setHoveredCard(null)}
                  className="group"
                >
                  <motion.div className="h-full">
                  <Card className={`border-2 border-gray-200 hover:border-primary transition-all duration-300 overflow-hidden bg-white relative h-full flex flex-col shadow-xl hover:shadow-2xl ${hasLinkedIn ? 'cursor-pointer' : ''}`}
                    onClick={() => {
                      if (hasLinkedIn && action.linkedInUrl) {
                        setSelectedAction(action)
                        setModalLinkedInUrl(action.linkedInUrl)
                      }
                    }}
                  >
                    <motion.div
                      className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full z-20"
                      transition={{ duration: 0.8 }}
                      style={{ display: isHovered ? 'block' : 'none' }}
                    />

                    <div className="relative aspect-video w-full overflow-hidden bg-gradient-to-br from-gray-100 to-gray-200">
                      {action.video ? (
                        <div className="relative w-full h-full">
                          <video
                            src={action.video}
                            className="w-full h-full object-cover"
                            muted
                            loop
                            playsInline
                          />
                          <div className="absolute inset-0 flex items-center justify-center bg-black/40 group-hover:bg-black/30 transition-colors">
                            <motion.div
                              className="w-20 h-20 rounded-full bg-white/95 flex items-center justify-center shadow-2xl"
                              whileHover={{ scale: 1.1 }}
                              whileTap={{ scale: 0.95 }}
                            >
                              <Play className="text-primary ml-1" size={28} />
                            </motion.div>
                          </div>
                        </div>
                      ) : (
                        <motion.div
                          className="relative w-full h-full"
                          whileHover={{ scale: 1.1 }}
                          transition={{ duration: 0.5 }}
                        >
                          <Image
                            src={action.image || '/media/generique.jpg'}
                            alt={isEn ? action.titleEn : action.title}
                            fill
                            className="object-cover"
                            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                            onError={(e) => {
                              const target = e.target as HTMLImageElement
                              target.src = '/media/generique.jpg'
                            }}
                          />
                          <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                        </motion.div>
                      )}

                      {!hideCategoryTags && (
                        <motion.div
                          className={`absolute top-4 left-4 ${colors.bg} text-white px-4 py-2 rounded-full text-xs font-bold flex items-center gap-2 shadow-lg backdrop-blur-sm z-10`}
                          whileHover={{ scale: 1.05 }}
                          animate={inView2 ? {
                            y: [0, -5, 0]
                          } : {}}
                          transition={{
                            y: {
                              duration: 2 + index * 0.2,
                              repeat: Number.POSITIVE_INFINITY,
                              ease: "easeInOut",
                              delay: index * 0.3
                            }
                          }}
                        >
                          <Icon size={16} />
                          <span>{t(`categories.${action.category}`)}</span>
                        </motion.div>
                      )}

                      {hasLinkedIn && (
                        <motion.div
                          className="absolute bottom-4 right-4 bg-white/90 backdrop-blur-sm px-4 py-2 rounded-full flex items-center gap-2 text-sm font-semibold text-gray-900 opacity-0 group-hover:opacity-100 transition-opacity duration-300 z-10"
                          whileHover={{ x: 5 }}
                        >
                          <span>{tActualite('viewLinkedInPost')}</span>
                          <ArrowRight size={16} />
                        </motion.div>
                      )}
                    </div>

                    <CardContent className="p-6 sm:p-8 relative z-10 bg-white flex-1 flex flex-col">
                      <div className="flex items-center gap-2 text-sm text-muted-foreground mb-4">
                        <Calendar className="text-primary" size={16} />
                        <span>{new Date(action.date).toLocaleDateString(isEn ? 'en-US' : 'fr-FR', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
                        {action.location && (
                          <>
                            <span className="text-primary">•</span>
                            <div className="flex items-center gap-1">
                              <MapPin size={14} />
                              <span>{action.location}</span>
                            </div>
                          </>
                        )}
                      </div>

                      <p className="text-muted-foreground leading-relaxed mb-4 line-clamp-4">
                        {isEn ? action.descriptionEn : action.description}
                      </p>

                      <div className="h-1 bg-gray-200 rounded-full overflow-hidden mt-2">
                        <motion.div
                          className={`h-full bg-gradient-to-r ${colors.gradient}`}
                          initial={{ width: 0 }}
                          whileInView={{ width: "100%" }}
                          viewport={{ once: true }}
                          transition={{ duration: 1, delay: 0.5 + index * 0.1 }}
                        />
                      </div>
                    </CardContent>
                  </Card>
                  </motion.div>
                </motion.div>
              )
            })}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <nav
              className="mt-12 flex flex-wrap items-center justify-center gap-2"
              aria-label="Pagination"
            >
              <button
                type="button"
                onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
                disabled={currentPage <= 1 || isChangingPage}
                className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:pointer-events-none transition-colors"
                aria-label={t('paginationPrevious')}
              >
                <ChevronLeft className="w-4 h-4" />
                {t('paginationPrevious')}
              </button>
              <div className="flex items-center gap-1">
                {(() => {
                  const maxVisiblePages = 3
                  let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2))
                  let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1)
                  
                  // Ajuster si on est à la fin
                  if (endPage - startPage + 1 < maxVisiblePages) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1)
                  }
                  
                  const pages = []
                  for (let i = startPage; i <= endPage; i++) {
                    pages.push(i)
                  }
                  
                  return pages.map((page) => (
                    <button
                      key={page}
                      type="button"
                      onClick={() => handlePageChange(page)}
                      disabled={isChangingPage}
                      className={`min-w-[2.5rem] h-10 px-2 rounded-lg text-sm font-medium transition-colors ${
                        currentPage === page
                          ? 'bg-primary text-white border border-primary'
                          : 'border border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
                      } ${isChangingPage ? 'opacity-50 pointer-events-none' : ''}`}
                      aria-label={`${t('paginationPage')} ${page}`}
                      aria-current={currentPage === page ? 'page' : undefined}
                    >
                      {page}
                    </button>
                  ))
                })()}
              </div>
              <button
                type="button"
                onClick={() => handlePageChange(Math.min(totalPages, currentPage + 1))}
                disabled={currentPage >= totalPages || isChangingPage}
                className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:pointer-events-none transition-colors"
                aria-label={t('paginationNext')}
              >
                {t('paginationNext')}
                <ChevronRight className="w-4 h-4" />
              </button>
            </nav>
          )}
          </>
        )}
        </div>
      </section>

      <Dialog open={!!modalLinkedInUrl} onOpenChange={(open) => {
        if (!open) {
          setModalLinkedInUrl(null)
          setSelectedAction(null)
        }
      }}>
        <DialogContent className="sm:max-w-[90vw] md:max-w-4xl h-[85vh] flex flex-col p-0 gap-0">
          <DialogTitle className="sr-only">Post LinkedIn</DialogTitle>
          <div className="flex-1 min-h-0 flex flex-col">
            {modalLinkedInUrl && (
              <>
                <iframe
                  src={getLinkedInEmbedUrl(modalLinkedInUrl)}
                  title="Post LinkedIn"
                  className="w-full flex-1 min-h-[400px] border-0 rounded-b-lg"
                  sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
                />
                <div className="p-4 border-t bg-muted/30 flex justify-end">
                  <a
                    href={modalLinkedInUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 text-sm font-semibold text-primary hover:underline"
                  >
                    <ExternalLink size={16} />
                    {tActualite('openOnLinkedIn')}
                  </a>
                </div>
              </>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </main>
  )
}
