import { useRef, useState } from 'react'
import Image from 'next/image'
import { AnimatePresence, m, useInView } from 'framer-motion'

import { DEFAULT_SPRING_TRANSITION } from '@/lib/constants'
import { useInterval } from '@/lib/hooks'

import AnimateUnderline from '@/components/shared/AnimateUnderline'
import Container from '@/components/shared/Container'

type Props = {
  title?: string
  content?: string
  logos: any[]
}

export default function TrustedPartners({ title, content, logos }: Props) {
  const [page, setPage] = useState(0)
  const containerRef = useRef<HTMLDivElement>(null)
  const isInView = useInView(containerRef)

  useInterval(() => {
    isInView && setPage(prev => prev + 1)
  }, 5000)

  return (
    <section className="py-24 text-white bg-black">
      <Container>
        <AnimateUnderline className="inline-block">{title}</AnimateUnderline>

        <p className="pt-8 text-section-intro">{content}</p>

        <div
          ref={containerRef}
          className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-y-12 sm:gap-y-16 pt-16 sm:pt-24"
        >
          <AnimatePresence initial={false}>
            {logos.map((item: any, index: number) => {
              const images = [item.logoImage, item.logoImageTwo]
              const activeImage = images[page % 2]

              return (
                <div
                  key={index}
                  className="overflow-hidden border-l border-gray-dark max-sm:[&:nth-child(2n)]:border-r sm:max-md:[&:nth-child(3n)]:border-r md:[&:nth-child(5n)]:border-r last:border-r"
                >
                  <div className="flex items-center justify-center">
                    <m.div
                      key={`${index}-${page}`}
                      initial={{ x: '100%' }}
                      animate={{ x: 0 }}
                      exit={{ x: '-100%' }}
                      transition={DEFAULT_SPRING_TRANSITION}
                      className="relative flex-shrink-0 aspect-16/9 w-4/5"
                    >
                      <Image src={activeImage.imageUrl} alt={activeImage.alt} fill className="object-cover" />
                    </m.div>
                  </div>
                </div>
              )
            })}
          </AnimatePresence>
        </div>
      </Container>
    </section>
  )
}
