"use client"
import { useState, useRef, useEffect, useCallback } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { timelineYears } from '../data/timelineSlides'
import type { AboutTimelineData } from '@/lib/strapi/types'

interface TimelineContent {
  body?: string
}

interface TimelineSlide extends TimelineContent {
  image: string
}

interface TimelineEntry extends TimelineContent {
  year: string
  image: string
  slides?: TimelineSlide[]
}

function resolveTimelineBody(item: TimelineContent): string {
  return item.body ?? ''
}

function TimelineDescription({
  content,
  size,
}: {
  content: TimelineContent
  size: 'mobile' | 'desktop'
}) {
  const body = resolveTimelineBody(content)
  const textClass = size === 'mobile' ? 'text-[14px] leading-[18px]' : 'text-[16px] leading-[20px]'

  return (
    <p
      className={`relative z-10 text-[#4a5565] font-medium break-words ${textClass} ${size === 'desktop' ? 'max-w-[472px]' : 'max-w-full'}`}
      style={{ overflowWrap: 'anywhere' }}
    >
      {body}
    </p>
  )
}

function buildTimelineData(
  years: { year: string; slides: { image: string; body: string }[] }[],
): TimelineEntry[] {
  return years
    .filter((y) => y.slides.length > 0)
    .map(({ year, slides }) => {
      const first = slides[0]
      if (slides.length <= 1) {
        return { year, image: first.image, body: first.body }
      }
      return {
        year,
        image: first.image,
        body: first.body,
        slides: slides.map((s) => ({ image: s.image, body: s.body })),
      }
    })
}

export default function TimelineSection({ data }: { data: AboutTimelineData }) {
  const badge = data.badge || 'Timeline'
  const badgeIcon = data.badgeIcon || '/assets/about/timeline-badge-icon.svg'
  const backgroundImage = data.backgroundImage || '/assets/about/timeline-bg.png'
  const cardVector = '/assets/about/timeline-card-vector.svg'

  const [activeTimeline, setActiveTimeline] = useState(0)
  const [activeSlide, setActiveSlide] = useState(0)
  const yearsScrollRef = useRef<HTMLDivElement>(null)

  const timelineData = buildTimelineData(data.years.length > 0 ? data.years : timelineYears)
  const safeTimeline = Math.min(activeTimeline, Math.max(timelineData.length - 1, 0))
  const currentTimeline = timelineData[safeTimeline] ?? { year: '', image: '', body: '' }
  const slides = currentTimeline.slides ?? null
  const safeSlideIndex = slides ? Math.min(activeSlide, slides.length - 1) : 0
  const displayContent: TimelineContent = slides ? slides[safeSlideIndex] : currentTimeline
  const showPointDots = slides && slides.length > 1

  useEffect(() => {
    const id = window.setTimeout(() => setActiveSlide(0), 0)
    return () => window.clearTimeout(id)
  }, [activeTimeline])

  useEffect(() => {
    if (!showPointDots) return
    const interval = setInterval(() => {
      setActiveSlide((prev) => (prev + 1) % slides!.length)
    }, 6000)
    return () => clearInterval(interval)
  }, [showPointDots, slides, activeTimeline])

  const handleTimelinePrev = useCallback(() => {
    setActiveTimeline((prev) => (prev > 0 ? prev - 1 : 0))
  }, [])

  const handleTimelineNext = useCallback(() => {
    setActiveTimeline((prev) => (prev < timelineData.length - 1 ? prev + 1 : timelineData.length - 1))
  }, [])

  useEffect(() => {
    if (yearsScrollRef.current) {
      const container = yearsScrollRef.current
      const activeBtn = container.children[activeTimeline] as HTMLElement
      if (activeBtn) {
        const containerRect = container.getBoundingClientRect()
        const btnRect = activeBtn.getBoundingClientRect()
        const offset = btnRect.left - containerRect.left - containerRect.width / 2 + btnRect.width / 2
        container.scrollBy({ left: offset, behavior: 'smooth' })
      }
    }
  }, [activeTimeline])

  if (timelineData.length === 0) return null

  return (
    <div className="w-full relative rounded-t-[28px] lg:rounded-t-[40px] overflow-hidden" style={{ contain: 'layout' }}>
      <div className="absolute inset-0 pointer-events-none">
        <img
          src={backgroundImage}
          alt=""
          loading="lazy"
          className="absolute w-full h-[110%] top-[-20%] left-0 object-cover"
        />
        <div
          className="absolute inset-0"
          style={{ background:
              'linear-gradient(180deg, rgba(42,48,54,0) 80.5%, rgb(42,48,54) 90.4%), linear-gradient(90deg, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.6) 100%), linear-gradient(90deg, rgba(42,48,54,0.7) 0%, rgba(42,48,54,0.7) 100%)',
          }}
        />
      </div>

      <div className="relative z-10 flex flex-col gap-[40px] px-[20px] lg:px-[72px] py-[40px]">
        <div className="max-w-[1297px] mx-auto w-full overflow-hidden flex flex-col gap-[24px] lg:gap-[40px]">
          <div className="flex items-center justify-between">
            <span
              className="font-heading inline-flex items-center gap-2 px-[24px] py-[12px] bg-white rounded-[66px] text-[16px] text-[#102443] uppercase"
            >
              <img src={badgeIcon} alt="" loading="lazy" className="w-[17px] h-[16px]" />
              {badge}
            </span>
            <div className="flex gap-[12px] lg:gap-[8px] items-center">
              <button
                onClick={handleTimelinePrev}
                disabled={activeTimeline === 0}
                className={`flex items-center justify-center w-[44px] h-[44px] lg:w-[60px] lg:h-[58px] rounded-full border-2 border-white transition-all active:scale-95 ${activeTimeline === 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:bg-white/10'}`}
                aria-label="Previous timeline"
              >
                <ChevronLeft size={20} strokeWidth={1.5} className="text-white" />
              </button>
              <button
                onClick={handleTimelineNext}
                disabled={activeTimeline === timelineData.length - 1}
                className={`flex items-center justify-center w-[44px] h-[44px] lg:w-[60px] lg:h-[58px] rounded-full border-2 border-white transition-all active:scale-95 ${activeTimeline === timelineData.length - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:bg-white/10'}`}
                aria-label="Next timeline"
              >
                <ChevronRight size={20} strokeWidth={1.5} className="text-white" />
              </button>
            </div>
          </div>

          <div className={`relative ${slides ? 'min-h-[384px] lg:min-h-[354px]' : 'min-h-[354px] lg:min-h-[314px]'}`}>
            <div key={currentTimeline.year} className="absolute left-0 top-0 w-full lg:max-w-[558px] h-[314px] rounded-[16px] overflow-hidden">
              {slides ? (
                slides.map((slide, i) => (
                  <img
                    key={`${currentTimeline.year}-${i}`}
                    src={slide.image}
                    alt={`Timeline ${currentTimeline.year}`}
                    className={`absolute inset-0 w-full h-full object-cover rounded-[16px] transition-opacity duration-700 ease-in-out ${
                      i === activeSlide ? 'opacity-100 z-10' : 'opacity-0 z-0'
                    }`}
                    loading={i === 0 ? 'lazy' : 'eager'}
                    draggable={false}
                  />
                ))
              ) : (
                <img
                  src={currentTimeline.image}
                  alt={`Timeline ${currentTimeline.year}`}
                  className="w-full h-full object-cover rounded-[16px]"
                  loading="lazy"
                  draggable={false}
                />
              )}
            </div>

            <div
              className="lg:hidden absolute left-[8px] top-[210px] w-[257px] rounded-[16px] border border-[#e5e7eb] p-[20px] overflow-hidden z-10"
              style={{ background:
                  'radial-gradient(ellipse at 42% 84%, rgba(244,247,251,0) 0%, rgba(244,247,251,1) 100%), linear-gradient(90deg, #fff 0%, #fff 100%)',
              }}
            >
              <img
                src={cardVector}
                alt=""
                loading="lazy"
                className="absolute pointer-events-none select-none"
                style={{ width: '297px',
                  height: '286px',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(calc(-50% + 108px), calc(-50% - 306px)) rotate(24.98deg)',
                }}
                aria-hidden="true"
              />
              <TimelineDescription content={displayContent} size="mobile" />
            </div>

            <div className="hidden lg:block absolute left-[557px] top-[63px] w-[364px] h-px bg-white/50" />

            <div
              className="hidden lg:block absolute left-[838px] top-[24px]"
            >
              <p className="text-[30px] text-white tracking-[-1.2px] leading-normal">{currentTimeline.year}</p>
            </div>

            <div className="hidden lg:flex absolute left-[921px] top-[49px] items-center justify-center w-[28px] h-[28px] rounded-full border border-white">
              <div className="w-[12px] h-[12px] rounded-full bg-white" />
            </div>

            <div
              className="absolute left-[590px] top-[144px] w-[627px] hidden lg:flex flex-col overflow-hidden rounded-[16px] border border-[#e5e7eb] p-[33px]"
              style={{ background:
                  'radial-gradient(ellipse at 42% 84%, rgba(244,247,251,0) 0%, rgba(244,247,251,1) 100%), linear-gradient(90deg, #fff 0%, #fff 100%)',
              }}
            >
              <img
                src={cardVector}
                alt=""
                loading="lazy"
                className="absolute pointer-events-none select-none"
                style={{ width: '297px',
                  height: '286px',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(calc(-50% + 227px), calc(-50%)) rotate(24.98deg)',
                }}
                aria-hidden="true"
              />
              <TimelineDescription content={displayContent} size="desktop" />
            </div>

            {showPointDots && (
              <div className="absolute left-0 lg:left-0 top-[334px] w-full lg:w-[558px] flex items-center justify-center gap-[8px]">
                {slides!.map((_, i) => (
                  <button
                    key={i}
                    onClick={() => setActiveSlide(i)}
                    className={`rounded-full transition-all duration-300 ${
                      i === activeSlide ? 'w-[24px] h-[8px] bg-white' : 'w-[8px] h-[8px] bg-white/40 hover:bg-white/60'
                    }`}
                    aria-label={`Go to point ${i + 1}`}
                  />
                ))}
              </div>
            )}
          </div>

          <div className="flex flex-col gap-[20px] mt-[20px] lg:mt-[40px]">
            <div className="w-full h-px bg-[rgba(235,235,235,0.5)]" />

            <div
              ref={yearsScrollRef}
              className="flex items-center gap-[60px] overflow-x-auto scrollbar-hide w-full"
              style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
            >
              {timelineData.map((item, i) => (
                <button
                  key={item.year}
                  onClick={() => setActiveTimeline(i)}
                  className={`px-[20px] py-[2px] rounded-[66px] text-[16px] lg:text-[20px] font-semibold tracking-[-1px] text-center whitespace-nowrap transition-all flex-shrink-0 ${
                    i === activeTimeline
                      ? 'border-2 border-white text-white'
                      : 'border border-[rgba(219,219,219,0.4)] text-[#757575] hover:border-[rgba(219,219,219,0.7)] hover:text-[#999]'
                  }`}
                  style={{ fontFeatureSettings: "'dlig' 1",
                  }}
                >
                  {item.year}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

