'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { ArrowRight, ChevronLeft, ChevronRight } from 'lucide-react'
import Image from 'next/image'
import { siteConfig, siteImages, heroSlides, getYearsOfExcellence } from '@/lib/site-config'

const SLIDE_INTERVAL_MS = 8000

export function Hero() {
  const years = getYearsOfExcellence()
  const [current, setCurrent] = useState(0)
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([])

  const goTo = useCallback(
    (index: number) => setCurrent((index + heroSlides.length) % heroSlides.length),
    [],
  )
  const prev = useCallback(() => goTo(current - 1), [current, goTo])
  const next = useCallback(() => goTo(current + 1), [current, goTo])

  useEffect(() => {
    const timer = window.setInterval(() => {
      setCurrent((c) => (c + 1) % heroSlides.length)
    }, SLIDE_INTERVAL_MS)
    return () => window.clearInterval(timer)
  }, [])

  useEffect(() => {
    heroSlides.forEach((slide, index) => {
      if (slide.type !== 'video') return

      const video = videoRefs.current[index]
      if (!video) return

      if (index === current) {
        video.currentTime = 0
        void video.play().catch(() => {})
      } else {
        video.pause()
      }
    })
  }, [current])

  const currentSlide = heroSlides[current]

  return (
    <section className="relative w-full min-h-[85vh] md:min-h-[92vh] overflow-hidden flex items-center">
      <div className="absolute inset-0 z-0">
        {heroSlides.map((slide, index) => (
          <div
            key={`${slide.type}-${slide.src}`}
            className={`absolute inset-0 transition-opacity duration-1000 ease-in-out ${
              index === current ? 'opacity-100 z-10' : 'opacity-0 z-0 pointer-events-none'
            }`}
            aria-hidden={index !== current}
          >
            {slide.type === 'video' ? (
              <video
                ref={(el) => {
                  videoRefs.current[index] = el
                }}
                src={slide.src}
                poster={slide.poster}
                muted
                loop
                playsInline
                preload={index === 0 ? 'auto' : 'metadata'}
                className="absolute inset-0 h-full w-full object-cover"
                aria-label={slide.alt}
              />
            ) : (
              <Image
                src={slide.src}
                alt={slide.alt}
                fill
                sizes="100vw"
                className="object-cover"
                priority={index <= 2}
              />
            )}
          </div>
        ))}

        <div className="absolute inset-0 z-20 pointer-events-none bg-gradient-to-r from-black/75 via-black/45 to-transparent" />
        <div className="absolute inset-0 z-20 pointer-events-none bg-gradient-to-t from-black/55 via-transparent to-transparent" />
      </div>

      <div className="relative z-30 w-full">
        <div className="container-wide py-20 md:py-32">
          <div className="max-w-3xl space-y-7 animate-fade-up">
            <div className="inline-flex items-center rounded-lg bg-white px-4 py-2.5">
              <Image
                src={siteImages.logo}
                alt={siteConfig.shortName}
                width={160}
                height={44}
                className="h-10 w-auto"
              />
            </div>

            <p className="text-accent font-semibold text-sm uppercase tracking-[0.25em] drop-shadow-md">
              {siteConfig.tagline}
            </p>

            <h1 className="text-4xl sm:text-5xl lg:text-[3.25rem] font-bold text-white leading-[1.1] text-balance drop-shadow-lg">
              {siteConfig.fullName}
            </h1>

            <p className="text-lg md:text-xl text-white/95 leading-relaxed max-w-2xl drop-shadow-md">
              {siteConfig.description}
            </p>

            <div className="flex flex-col sm:flex-row gap-4 pt-2">
              <Link href="/services/upcoming-courses">
                <Button
                  size="lg"
                  className="bg-accent text-accent-foreground hover:bg-accent/90 font-semibold h-12 px-8 w-full sm:w-auto"
                >
                  Explore Courses
                  <ArrowRight className="ml-2 w-4 h-4" />
                </Button>
              </Link>
              <Link href="/contact">
                <Button
                  size="lg"
                  variant="outlineLight"
                  className="font-semibold h-12 px-8 w-full sm:w-auto"
                >
                  Get in Touch
                </Button>
              </Link>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-4 gap-6 pt-10 max-w-2xl">
              {[
                { value: '500+', label: 'Courses' },
                { value: '65+', label: 'Countries' },
                { value: `${years}+`, label: 'Years' },
                { value: '4.8★', label: 'Google Rating' },
              ].map((stat) => (
                <div key={stat.label} className="space-y-1">
                  <p className="text-2xl sm:text-3xl font-bold text-accent drop-shadow-md">{stat.value}</p>
                  <p className="text-white/80 text-xs sm:text-sm drop-shadow-sm">{stat.label}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="absolute bottom-8 left-0 right-0 z-30">
        <div className="container-wide flex items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            {heroSlides.map((slide, index) => (
              <button
                key={`dot-${slide.src}`}
                type="button"
                onClick={() => goTo(index)}
                className={`h-2 rounded-full transition-all duration-300 ${
                  index === current ? 'w-8 bg-accent' : 'w-2 bg-white/50 hover:bg-white/80'
                }`}
                aria-label={
                  slide.type === 'video'
                    ? `Go to video slide ${index + 1}`
                    : `Go to slide ${index + 1}`
                }
                aria-current={index === current ? 'true' : undefined}
              />
            ))}
          </div>

          <div className="flex items-center gap-2">
            <Button
              type="button"
              variant="outlineLight"
              size="icon"
              onClick={prev}
              className="size-10 rounded-full backdrop-blur-sm"
              aria-label="Previous slide"
            >
              <ChevronLeft className="w-5 h-5" />
            </Button>
            <Button
              type="button"
              variant="outlineLight"
              size="icon"
              onClick={next}
              className="size-10 rounded-full backdrop-blur-sm"
              aria-label="Next slide"
            >
              <ChevronRight className="w-5 h-5" />
            </Button>
          </div>
        </div>
      </div>

      <p className="sr-only" aria-live="polite">
        Showing slide {current + 1} of {heroSlides.length}: {currentSlide.alt}
      </p>
    </section>
  )
}
