'use client'

import React, { useEffect, useRef, useState } from 'react'
import { Section } from '@/components/ui/section'
import { FadeInText } from '@/components/shared/FadeInText'
import { StickyStackCards } from '@/components/shared/StickyStackCards'
import { Media, WhyChooseUsSection } from '@/payload-types'
import { useHasBeenVisible } from '@/lib/utils/hooks'
import ImageLoader from '@/lib/utils/ImageLoader'
import { AnimatePresence, motion } from 'framer-motion'
import GragientCard from '@/components/shared/cards/GragientCard'

interface Props extends WhyChooseUsSection {}

export const WhyChooseUs: React.FC<Props> = (props) => {
  const sectionRef = useRef<HTMLDivElement>(null)
  const [activeIndex, setActiveIndex] = useState<number>(0)

  const hasBeenVisible = useHasBeenVisible(sectionRef)

  useEffect(() => {
    const cards = props.cards || []
    if (cards.length === 0 || !hasBeenVisible) return
    function isMobile() {
      return window.innerWidth < 744
    }

    let index = 0
    let interval: NodeJS.Timeout

    function startAnimation() {
      if (isMobile()) {
        setActiveIndex(0)
      } else {
        interval = setInterval(() => {
          setActiveIndex(index)
          index = (index + 1) % cards.length
        }, 1500)
      }
    }

    startAnimation()
    window.addEventListener('resize', handleResize)

    function handleResize() {
      clearInterval(interval)
      startAnimation()
    }

    return () => {
      window.removeEventListener('resize', handleResize)
      clearInterval(interval)
    }
  }, [hasBeenVisible])

  return (
    <Section ref={sectionRef} sectionClass="py-[80px] md:py-[100px] lg:py-[120px]" boxClass="">
      <h2 className="subheadline-semibold md:h2 mb-8 text-base-white">
        <FadeInText text={props.title} canAnimate={hasBeenVisible} />
      </h2>
      <div className="hidden md:grid tablet:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-x-5 md:gap-y-4 lg:gap-4">
        {(props.cards || []).map((card, i) => (
          <GragientCard
            key={card.id}
            icon={card.icon}
            title={card.caption}
            type="small"
            isActive={activeIndex === i}
          />
        ))}
      </div>
      <div className="md:hidden ">
        <StickyStackCards className="mb-[100px]" onActiveIndexChange={setActiveIndex} cardGap={20}>
          {(props.cards || []).map((card, i) => (
            <GragientCard
              key={card.id}
              icon={card.icon}
              title={card.caption}
              type="small"
              isActive={activeIndex === i}
            />
          ))}
        </StickyStackCards>
      </div>
    </Section>
  )
}

// interface WhyChooseUsCardProps {
//   caption: string
//   icon: string | Media
//   isActive: boolean
// }

// const WhyChooseUsCard: React.FC<WhyChooseUsCardProps> = ({ caption, icon, isActive }) => {
//   return (
//     <div className="gradient-border gradient-border--white w-full p-4 bg-[#141210] md:bg-[#221D1A66] rounded-xl relative overflow-hidden">
//       <AnimatePresence mode="wait">
//         {isActive && (
//           <motion.div
//             key="glow"
//             className="absolute inset-0 overflow-hidden flex items-end justify-center pointer-events-none"
//             initial={{ opacity: 0 }}
//             animate={{ opacity: 1 }}
//             exit={{ opacity: 0 }}
//             transition={{ duration: 0.8, ease: 'easeInOut' }}
//           >
//             <div className="w-[244px] h-[44px] bg-[#D39E7F] rounded-full blur-[78px] opacity-80" />
//           </motion.div>
//         )}
//       </AnimatePresence>

//       <div className="bg-grey-700 p-2 w-fit rounded-full">
//         <ImageLoader width={32} height={32} media={icon} alt="" />
//       </div>
//       <h3 className="b1-regular mt-[48px] lg:mt-4 text-grey-100">{caption}</h3>
//     </div>
//   )
// }
export default WhyChooseUs
