"use client"

import { useState, useEffect, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { X } from "lucide-react"
import Image from "next/image"
import { useTranslations } from "next-intl"

// Images du carrousel en arrière-plan
const carouselImages = [
  "/bateau.jpg",
  "/agent.jpg",
  "/labo.jpg",
  "/sapeur.png",
]

// Fonction pour calculer le temps d'affichage en fonction de la longueur du message
const getMessageDisplayTime = (message: string): number => {
  // Base de 4 secondes + 50ms par caractère, avec un minimum de 5 secondes et un maximum de 10 secondes
  const baseTime = 4000
  const charTime = 50
  const calculatedTime = baseTime + (message.length * charTime)
  return Math.max(5000, Math.min(10000, calculatedTime))
}

export default function AnimatedCharacter() {
  const t = useTranslations('mai.messages')
  const tCommon = useTranslations('mai')
  
  // Créer le tableau de messages traduits
  const welcomeMessages = [
    t('message1'),
    t('message2'),
    t('message3'),
    t('message4'),
    t('message5'),
    t('message6'),
    t('message7'),
    t('message8'),
    t('message9'),
    t('message10'),
    t('message11'),
    t('message12'),
    t('message13'),
    t('message14'),
    t('message15'),
    t('message16'),
    t('message17'),
    t('message18'),
    t('message19'),
    t('message20'),
    t('message21'),
    t('message22'),
    t('message23'),
    t('message24'),
    t('message25'),
  ]

  const [currentMessageIndex, setCurrentMessageIndex] = useState(0)
  const [showChat, setShowChat] = useState(true)
  const [hasWelcomed, setHasWelcomed] = useState(false)
  const [isWaving, setIsWaving] = useState(true)
  const [currentImageIndex, setCurrentImageIndex] = useState(0)
  const timeoutRef = useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    const timer = setTimeout(() => {
      setHasWelcomed(true)
    }, 1000)
    return () => clearTimeout(timer)
  }, [])

  useEffect(() => {
    if (!hasWelcomed || !showChat) {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
        timeoutRef.current = null
      }
      return
    }

    // Nettoyer le timeout précédent
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }

    const currentMessage = welcomeMessages[currentMessageIndex]
    const displayTime = getMessageDisplayTime(currentMessage)

    timeoutRef.current = setTimeout(() => {
      if (currentMessageIndex < welcomeMessages.length - 1) {
        setCurrentMessageIndex((prev) => prev + 1)
      }
    }, displayTime)

    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
        timeoutRef.current = null
      }
    }
  }, [hasWelcomed, showChat, currentMessageIndex])

  useEffect(() => {
    // Arrêter le geste de la main après quelques secondes
    const timer = setTimeout(() => {
      setIsWaving(false)
    }, 4000)
    return () => clearTimeout(timer)
  }, [])

  // Carrousel d'images en arrière-plan
  useEffect(() => {
    const carouselInterval = setInterval(() => {
      setCurrentImageIndex((prev) => (prev + 1) % carouselImages.length)
    }, 4000) // Changer d'image toutes les 4 secondes

    return () => clearInterval(carouselInterval)
  }, [])

  const handleClose = () => {
    setShowChat(false)
  }

  return (
    <div className="fixed bottom-6 right-6 sm:bottom-8 sm:right-8 z-50 flex flex-col items-end gap-4">
      {/* Bulle de dialogue au-dessus */}
      <AnimatePresence>
        {showChat && (
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.8 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.8 }}
            transition={{ type: "spring", stiffness: 300, damping: 25, delay: 1 }}
            className="relative flex-shrink-0 mb-2"
          >
            <div className="bg-white rounded-xl sm:rounded-2xl shadow-2xl p-4 sm:p-5 md:p-6 max-w-xs sm:max-w-sm md:max-w-md border-2 border-primary/20 relative">
              {/* Bouton fermer */}
              <button
                onClick={handleClose}
                className="absolute top-2 right-2 w-6 h-6 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-colors z-10"
                aria-label={tCommon('closeButton')}
              >
                <X size={14} className="text-gray-600" />
              </button>

              {/* Contenu du message */}
              <AnimatePresence mode="wait">
                <motion.div
                  key={currentMessageIndex}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  transition={{ duration: 0.3 }}
                  className="pr-4 sm:pr-6"
                >
                  <p className="text-gray-800 text-sm sm:text-base leading-relaxed">
                    {welcomeMessages[currentMessageIndex]}
                  </p>
                </motion.div>
              </AnimatePresence>

              {/* Indicateur de frappe */}
              {currentMessageIndex < welcomeMessages.length - 1 && (
                <motion.div
                  className="flex gap-1 mt-3"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                >
                  {[0, 1, 2].map((i) => (
                    <motion.div
                      key={i}
                      className="w-2 h-2 bg-primary rounded-full"
                      animate={{
                        y: [0, -8, 0],
                        opacity: [0.5, 1, 0.5],
                      }}
                      transition={{
                        duration: 0.6,
                        repeat: Number.POSITIVE_INFINITY,
                        delay: i * 0.2,
                      }}
                    />
                  ))}
                </motion.div>
              )}

              {/* Pointe de la bulle pointant vers le bas (vers l'avatar) */}
              <div className="absolute bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2 w-6 h-6 bg-white border-b-2 border-r-2 border-primary/20 transform rotate-45" />
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Avatar en bas avec carrousel en arrière-plan */}
      <motion.div
        initial={{ opacity: 0, scale: 0.5, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        transition={{ type: "spring", stiffness: 200, damping: 20, delay: 0.5 }}
        className="relative z-10 flex-shrink-0 cursor-pointer"
        onClick={() => setShowChat(!showChat)}
      >
        {/* Carrousel d'images en arrière-plan avec effet de tranches */}
        <div className="absolute inset-0 -z-10 w-20 h-20 sm:w-24 sm:h-24 md:w-28 md:h-28 rounded-full overflow-hidden">
          <AnimatePresence mode="wait">
            <motion.div
              key={currentImageIndex}
              initial={{ opacity: 0, scale: 1.2, rotate: -10 }}
              animate={{ opacity: 0.7, scale: 1, rotate: 0 }}
              exit={{ opacity: 0, scale: 0.8, rotate: 10 }}
              transition={{ duration: 1.5, ease: "easeInOut" }}
              className="absolute inset-0"
            >
              <Image
                src={carouselImages[currentImageIndex]}
                alt={`Image ${currentImageIndex + 1}`}
                fill
                className="object-cover rounded-full"
                unoptimized
              />
              {/* Overlay pour améliorer la visibilité */}
              <div className="absolute inset-0 bg-gradient-to-br from-primary/30 via-transparent to-transparent rounded-full" />
            </motion.div>
          </AnimatePresence>
          
          {/* Effet de tranches dynamique - masque circulaire avec tranches */}
          <div className="absolute inset-0 rounded-full overflow-hidden">
            {Array.from({ length: 8 }).map((_, i) => (
              <motion.div
                key={i}
                className="absolute inset-0"
                style={{
                  clipPath: `polygon(50% 50%, ${50 + 50 * Math.cos((i * Math.PI * 2) / 8 - Math.PI / 2)}% ${50 + 50 * Math.sin((i * Math.PI * 2) / 8 - Math.PI / 2)}%, ${50 + 50 * Math.cos(((i + 1) * Math.PI * 2) / 8 - Math.PI / 2)}% ${50 + 50 * Math.sin(((i + 1) * Math.PI * 2) / 8 - Math.PI / 2)}%)`,
                }}
                animate={{
                  opacity: [0.3, 0.8, 0.3],
                }}
                transition={{
                  duration: 2,
                  repeat: Number.POSITIVE_INFINITY,
                  delay: i * 0.2,
                  ease: "easeInOut",
                }}
              >
                <div className="absolute inset-0 bg-white/20" />
              </motion.div>
            ))}
          </div>
        </div>

        <motion.div
          className="relative"
          animate={{ y: [0, -10, 0] }}
          transition={{ duration: 2, repeat: Number.POSITIVE_INFINITY, ease: "easeInOut" }}
        >
          <div className="relative w-20 h-20 sm:w-24 sm:h-24 md:w-28 md:h-28 rounded-full shadow-2xl overflow-hidden border-2 sm:border-3 md:border-4 border-primary bg-white z-10">
            <motion.div
              animate={isWaving ? {
                rotate: [0, 10, -10, 10, 0],
              } : {
                rotate: 0,
              }}
              transition={{
                duration: 0.5,
                repeat: isWaving ? 4 : 0,
                ease: "easeInOut"
              }}
              style={{ transformOrigin: "center center" }}
              className="w-full h-full"
            >
              <Image
                src="/saria-avatar.png"
                alt="Assistant SAR"
                fill
                className="object-cover"
                priority
              />
            </motion.div>
          </div>
          
          {/* Animation de pulsation autour de l'avatar */}
          <motion.div
            className="absolute inset-0 rounded-full border-4 border-primary/30"
            animate={{
              scale: [1, 1.2, 1],
              opacity: [0.5, 0, 0.5],
            }}
            transition={{
              duration: 2,
              repeat: Number.POSITIVE_INFINITY,
              ease: "easeInOut",
            }}
          />
        </motion.div>
      </motion.div>
    </div>
  )
}

