"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
import { useLocale } from "next-intl"
import SarLoader from "./sar-loader"

interface QuestionAnswer {
  question: string
  answer: string
}

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
const PER_PAGE = 3
const AUTO_INTERVAL = 5000

export default function VisiteGuideeBlock() {
  const locale = useLocale()
  const [qaList, setQaList] = useState<QuestionAnswer[]>([])
  const [loading, setLoading] = useState(true)
  const [openIndex, setOpenIndex] = useState<number | null>(null)
  const [page, setPage] = useState(0)
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const totalPages = Math.ceil(qaList.length / PER_PAGE)
  const pageItems = qaList.slice(page * PER_PAGE, (page + 1) * PER_PAGE)

  useEffect(() => {
    fetch(`${API_URL}/api/sar/questions?locale=${locale}`)
      .then(r => r.json())
      .then((data: QuestionAnswer[]) => {
        setQaList(Array.isArray(data) ? data : [])
        setLoading(false)
      })
      .catch(() => setLoading(false))
  }, [locale])

  const startInterval = useCallback(() => {
    if (intervalRef.current) clearInterval(intervalRef.current)
    intervalRef.current = setInterval(() => {
      setPage(Math.floor(Math.random() * totalPages))
      setOpenIndex(null)
    }, AUTO_INTERVAL)
  }, [totalPages])

  const stopInterval = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current)
      intervalRef.current = null
    }
  }, [])

  // Démarrer l'auto-pagination quand les données sont chargées
  useEffect(() => {
    if (totalPages < 2) return
    startInterval()
    return () => stopInterval()
  }, [totalPages, startInterval, stopInterval])

  // Pause quand une réponse est ouverte, reprise quand fermée
  useEffect(() => {
    if (totalPages < 2) return
    if (openIndex !== null) {
      stopInterval()
    } else {
      startInterval()
    }
  }, [openIndex, totalPages, startInterval, stopInterval])

  const goTo = (p: number) => {
    setPage(p)
    setOpenIndex(null)
    startInterval()
  }

  const toggle = (i: number) => setOpenIndex(prev => prev === i ? null : i)

  if (loading) return <SarLoader />
  if (qaList.length === 0) return null

  return (
    <div className="max-w-3xl mx-auto">

      {/* Liste FAQ */}
      <div className="space-y-2">
        {pageItems.map((qa, i) => {
          const isOpen = openIndex === i
          return (
            <div
              key={`${page}-${i}`}
              className={`border bg-white transition-shadow duration-200 ${
                isOpen
                  ? "border-neutral-200 border-l-4 border-l-primary shadow-sm"
                  : "border-neutral-200 border-l-4 border-l-primary/20"
              }`}
            >
              <button
                type="button"
                onClick={() => toggle(i)}
                className="w-full flex items-center justify-between gap-4 px-5 py-4 text-left"
              >
                <span className={`text-sm font-semibold leading-snug transition-colors ${
                  isOpen ? "text-gray-900" : "text-gray-700"
                }`}>
                  {qa.question}
                </span>
                <motion.span
                  animate={{ rotate: isOpen ? 180 : 0 }}
                  transition={{ duration: 0.2 }}
                  className="flex-shrink-0"
                >
                  <ChevronDown size={16} className={`transition-colors ${isOpen ? "text-primary" : "text-gray-400"}`} />
                </motion.span>
              </button>

              <AnimatePresence initial={false}>
                {isOpen && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: "auto", opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    transition={{ duration: 0.25, ease: "easeInOut" }}
                    className="overflow-hidden"
                  >
                    <div className="px-5 pb-5 border-t border-neutral-100">
                      <div className="h-0.5 w-10 bg-primary/70 mt-3 mb-3" aria-hidden />
                      <p className="text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">
                        {qa.answer}
                      </p>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          )
        })}
      </div>

      {/* Pagination + indicateur */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-5 pt-4 border-t border-neutral-100">
          <div className="flex items-center gap-3">
            <p className="text-xs font-semibold uppercase tracking-widest text-gray-400">
              Page {page + 1} / {totalPages}
            </p>
            {openIndex !== null && (
              <span className="text-[10px] font-medium text-primary/70 uppercase tracking-widest">
               , en pause
              </span>
            )}
          </div>
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => goTo((page - 1 + totalPages) % totalPages)}
              className="flex items-center gap-1.5 px-3 h-8 border border-gray-200 bg-white text-xs font-semibold text-gray-500 disabled:opacity-30 transition-colors hover:border-primary/40 hover:text-primary"
            >
              <ChevronLeft size={13} />
              Précédent
            </button>
            <button
              type="button"
              onClick={() => goTo((page + 1) % totalPages)}
              className="flex items-center gap-1.5 px-3 h-8 border border-gray-200 bg-white text-xs font-semibold text-gray-500 disabled:opacity-30 transition-colors hover:border-primary/40 hover:text-primary"
            >
              Suivant
              <ChevronRight size={13} />
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
