'use client'

import { useEffect, useRef, useState } from 'react'
import Image from 'next/image'
import { cn } from '@/lib/utils'
import { Text } from '@/components/ui'
import { SectionLabel } from '@/components/ui/sectionlabel'
import { useIsRtl } from '@/lib/use-is-rtl'
import type { BecomeAgentStep, SolutionsImage } from '@/types/solutions'

const TIMELINE_DOT_CENTER_OFFSET = 18

interface AgentTimelineProps {
  badge: string
  title: string
  description: string
  image: SolutionsImage
  steps: BecomeAgentStep[]
}

export function AgentTimeline({ badge, title, description, image, steps }: AgentTimelineProps) {
  const isRtl = useIsRtl()
  const [activeIndex, setActiveIndex] = useState(0)
  const [visibleActiveIndex, setVisibleActiveIndex] = useState(0)
  const [backgroundLineHeight, setBackgroundLineHeight] = useState(0)
  const [activeLineHeight, setActiveLineHeight] = useState(0)
  const [stepLineOffsets, setStepLineOffsets] = useState<number[]>([])
  const stepRefs = useRef<(HTMLDivElement | null)[]>([])
  const activeLineRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    let frameId: number | null = null

    const updateActiveStep = () => {
      frameId = null
      const activationPoint = window.innerHeight * 0.45
      let nextActiveIndex = 0
      let closestDistance = Number.POSITIVE_INFINITY

      stepRefs.current.forEach((element, index) => {
        if (!element) return

        const rect = element.getBoundingClientRect()
        const stepCenter = rect.top + TIMELINE_DOT_CENTER_OFFSET
        const distance = Math.abs(stepCenter - activationPoint)

        if (distance < closestDistance) {
          closestDistance = distance
          nextActiveIndex = index
        }
      })

      setActiveIndex((currentIndex) => (currentIndex === nextActiveIndex ? currentIndex : nextActiveIndex))
    }

    const scheduleUpdate = () => {
      if (frameId !== null) return
      frameId = window.requestAnimationFrame(updateActiveStep)
    }

    const timer = window.setTimeout(scheduleUpdate, 100)
    window.addEventListener('scroll', scheduleUpdate, { passive: true })
    window.addEventListener('resize', scheduleUpdate)

    return () => {
      window.clearTimeout(timer)
      if (frameId !== null) window.cancelAnimationFrame(frameId)
      window.removeEventListener('scroll', scheduleUpdate)
      window.removeEventListener('resize', scheduleUpdate)
    }
  }, [steps.length])

  useEffect(() => {
    const measure = () => {
      const first = stepRefs.current[0]
      const last = stepRefs.current[steps.length - 1]
      const active = stepRefs.current[activeIndex]
      if (!first || !last || !active) return

      const firstCenter = first.getBoundingClientRect().top + TIMELINE_DOT_CENTER_OFFSET
      const lastCenter = last.getBoundingClientRect().top + TIMELINE_DOT_CENTER_OFFSET
      const activeCenter = active.getBoundingClientRect().top + TIMELINE_DOT_CENTER_OFFSET
      const lineHeight = lastCenter - firstCenter
      const nextStepLineOffsets = stepRefs.current.slice(0, steps.length).map((element) => {
        if (!element) return 0

        return element.getBoundingClientRect().top + TIMELINE_DOT_CENTER_OFFSET - firstCenter
      })

      setBackgroundLineHeight(lineHeight)
      setStepLineOffsets(nextStepLineOffsets)
      setActiveLineHeight(Math.min(lineHeight, Math.max(0, activeCenter - firstCenter)))
    }

    const timer = window.setTimeout(measure, 100)
    window.addEventListener('resize', measure)
    return () => {
      window.clearTimeout(timer)
      window.removeEventListener('resize', measure)
    }
  }, [activeIndex, steps.length])

  useEffect(() => {
    const activeLine = activeLineRef.current
    if (!activeLine || stepLineOffsets.length === 0) return

    let frameId = 0

    const syncVisibleStep = () => {
      const currentLineHeight = activeLine.getBoundingClientRect().height
      const nextVisibleIndex = stepLineOffsets.reduce((visibleIndex, offset, index) => (
        currentLineHeight + 1 >= offset ? index : visibleIndex
      ), 0)

      setVisibleActiveIndex((currentIndex) => (currentIndex === nextVisibleIndex ? currentIndex : nextVisibleIndex))

      if (Math.abs(currentLineHeight - activeLineHeight) > 1) {
        frameId = window.requestAnimationFrame(syncVisibleStep)
      }
    }

    frameId = window.requestAnimationFrame(syncVisibleStep)

    return () => {
      window.cancelAnimationFrame(frameId)
    }
  }, [activeLineHeight, stepLineOffsets])

  const imageWidth = Number(image.width) || 490
  const imageHeight = Number(image.height) || 890

  return (
   <div className='stackinline'>
     <div className='bg-[#F5F5F5] '>
      <div className='py-20 md:py-24 xl:py-[150px] container'>
        <SectionLabel
          label={badge}
          textclass='text-center mx-auto'
          className='flex-center flex-col'
          title={<span dangerouslySetInnerHTML={{ __html: title.replace('<span>', '<span class="gradient-text-green">') }} />}
          description={description}
        />

        <div
          dir='ltr'
          className={cn(
            'flex flex-col gap-10 lg:gap-16 stackinline justify-center',
            isRtl ? 'lg:flex-row-reverse' : 'lg:flex-row',
          )}
        >
          <div className='flex justify-center lg:sticky top-32 '>
            {image.url && (
              <Image
                src={image.url}
                alt={image.alt || title || badge}
                width={imageWidth}
                height={imageHeight}
                className='h-[400px] object-contain w-full lg:h-[890px] lg:w-[490px]'
              />
            )}
          </div>

          <div className='relative'>
            <div
              className={cn('absolute top-[18px] w-0.5 bg-[#DFDFDF]', isRtl ? 'left-[25px] lg:left-auto lg:right-[22px]' : 'left-[26px]')}
              style={{ height: backgroundLineHeight }}
            />
            <div
              ref={activeLineRef}
              className={cn(
                'absolute top-[18px] w-0.5 bg-[#2D643A] transition-all duration-1000 ease-in-out will-change-[height]',
                isRtl ? 'left-[25px]  lg:left-auto lg:right-[22px]' : 'left-[26px]',
              )}
              style={{ height: activeLineHeight }}
            />

            <div className='space-y-18 lg:space-y-24'>
              {steps.map((step, index) => {
                const isActive = index <= visibleActiveIndex
                return (
                  <div
                    key={`${step.title}-${index}`}
                    ref={(element) => { stepRefs.current[index] = element }}
                    className={cn('flex gap-6 lg:gap-[120px] items-start', isRtl && 'lg:flex-row-reverse')}
                  >
                    <div className='relative z-10 flex-shrink-0'>
                      <div className='absolute -inset-1 bg-[#F5F5F5] rounded-full' />
                      <div
                        className={cn(
                          'relative size-[50px] rounded-full border-2 flex items-center justify-center transition-all duration-200',
                          isActive ? 'border-[#2D643A] bg-[#2D643A]' : 'border-[#DFDFDF] bg-[#F5F5F5]',
                        )}
                      >
                        <Text
                          size='subtitle'
                          fontWeight={600}
                          className={cn('transition-colors duration-200', isActive ? 'text-white' : 'text-black')}
                          textKey={String(index + 1).padStart(2, '0')}
                        />
                      </div>
                    </div>

                    <div dir={isRtl ? 'rtl' : 'ltr'} className={cn('space-y-[15px]', isRtl && 'text-right')}>
                      <Text size='h3' fontWeight={600} className='text-[#101010]' textKey={step.title} />
                      <Text size='normal' className='max-w-md text-[#616161]' textKey={step.description} />
                    </div>
                  </div>
                )
              })}
           
            </div>
          </div>
        </div>
      </div>
    </div>
   </div>
  )
}
