'use client';

import React, { useCallback, useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { AnimatePresence, motion, useReducedMotion } from 'motion/react';
import api from '@/lib/api';

export type HeroStat = {
  value: string;
  label: string;
};

export type HeroSlide = {
  id: number | string;
  badge?: string | null;
  title: string;
  subtitle?: string | null;
  primary_button_text?: string | null;
  primary_button_link?: string | null;
  secondary_button_text?: string | null;
  secondary_button_link?: string | null;
  stats?: HeroStat[] | null;
  image?: string | null;
  image_large?: string | null;
  image_medium?: string | null;
};

const AUTOPLAY_MS = 7000;

const FALLBACK_SLIDES: HeroSlide[] = [
  {
    id: 'fallback-1',
    badge: 'When a Girl Learns',
    title: 'The World Rises',
    subtitle:
      'Unlocking potential, transforming communities. SSEOA creates educational opportunities for girls and women in remote regions of Afghanistan.',
    primary_button_text: 'Donate Now',
    primary_button_link: '/donate',
    secondary_button_text: 'Learn More',
    secondary_button_link: '/about-us',
    image: '/images/hero/slider-1.webp',
    stats: [
      { value: '2,000+', label: 'Education Support' },
      { value: '1,500+', label: 'Kankor Preparation' },
      { value: '1,200+', label: 'Early Childhood Development' },
    ],
  },
  {
    id: 'fallback-2',
    badge: 'Every Educated Girl',
    title: 'Plants a Seed of Change',
    subtitle:
      'Building leaders through learning — Community-Based Education, ECD, and classrooms where schools cannot reach.',
    primary_button_text: 'Our Programs',
    primary_button_link: '/programs/education',
    secondary_button_text: 'Read Stories',
    secondary_button_link: '/blog?category=story',
    image: '/images/hero/slider-2.webp',
    stats: [
      { value: '3,130', label: 'CBE Students' },
      { value: '1,800+', label: 'Vocational & Literacy' },
      { value: '1,017', label: 'Teachers Recruited' },
    ],
  },
  {
    id: 'fallback-3',
    badge: 'From Classrooms to Communities',
    title: 'She Transforms All',
    subtitle:
      'Empowering girls is empowering generations. Livelihood skills, literacy, and education that help families thrive.',
    primary_button_text: 'Get Involved',
    primary_button_link: '/#get-involved',
    secondary_button_text: 'What We Do',
    secondary_button_link: '/#what-we-do',
    image: '/images/hero/slider-3.webp',
    stats: [
      { value: '105,081', label: 'Girls Reached' },
      { value: '1,445', label: 'Women in Literacy' },
      { value: '10', label: 'Provinces' },
    ],
  },
];

const STAT_ICONS = [
  <path
    key="cap"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth={1.75}
    d="M4.26 10.146a60.44 60.44 0 00-.491 6.347A48.628 48.628 0 0112 20.904a48.628 48.628 0 018.232-4.41 60.46 60.46 0 00-.491-6.347m-15.482 0a50.57 50.57 0 00-2.658-.813A59.906 59.906 0 0112 3.493a59.903 59.903 0 0110.399 5.84c-.896.248-1.783.52-2.658.814m-15.482 0A50.697 50.697 0 0112 13.489a50.702 50.702 0 017.74-3.342M6.75 15a.75.75 0 100-1.5.75.75 0 000 1.5zm0 0v-3.675A55.378 55.378 0 0112 8.443m-7.007 11.55A5.981 5.981 0 006.75 15.75v-1.5"
  />,
  <path
    key="book"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth={1.75}
    d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25"
  />,
  <path
    key="users"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth={1.75}
    d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z"
  />,
];

function isExternalLink(href: string) {
  return /^https?:\/\//i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:');
}

function HeroCtaLink({ href, children }: { href: string; children: React.ReactNode }) {
  if (isExternalLink(href)) {
    return (
      <a href={href} target="_blank" rel="noopener noreferrer">
        {children}
      </a>
    );
  }

  return <Link href={href}>{children}</Link>;
}

function slideImage(slide?: HeroSlide | null) {
  return slide?.image_large || slide?.image_medium || slide?.image || '/images/hero/slider-1.webp';
}

function SlidePhoto({
  src,
  alt,
  priority = false,
  className = 'object-cover object-center',
}: {
  src: string;
  alt: string;
  priority?: boolean;
  className?: string;
}) {
  if (src.startsWith('http')) {
    // eslint-disable-next-line @next/next/no-img-element
    return <img src={src} alt={alt} className={`absolute inset-0 h-full w-full ${className}`} />;
  }

  return (
    <Image
      src={src}
      alt={alt}
      fill
      priority={priority}
      className={className}
      sizes="100vw"
      quality={90}
    />
  );
}

function HighlightTitle({ title }: { title: string }) {
  const words = title.trim().split(/\s+/);
  const last = words.pop() ?? title;
  const rest = words.join(' ');

  return (
    <h1 className="text-[1.85rem] font-black leading-[1.08] tracking-tight sm:text-4xl md:text-5xl lg:text-[3.25rem]">
      {rest ? <span className="block text-white">{rest}</span> : null}
      <span className="text-primary-500">{last}</span>
    </h1>
  );
}

/**
 * Full-bleed hero — active slide fills the viewport; smaller thumbnails for navigation.
 */
export const Hero: React.FC = () => {
  const reduceMotion = useReducedMotion();
  const [slides, setSlides] = useState<HeroSlide[]>(FALLBACK_SLIDES);
  const [loading, setLoading] = useState(true);
  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(1);
  const [userPaused, setUserPaused] = useState(false);
  const [hoverPaused, setHoverPaused] = useState(false);
  const [progressKey, setProgressKey] = useState(0);

  const paused = userPaused || hoverPaused;

  useEffect(() => {
    let cancelled = false;

    const loadSlides = async () => {
      try {
        setLoading(true);
        const response: unknown = await api.getHeroSlides({ status: 'active' });

        let data: HeroSlide[] = [];
        if (Array.isArray(response)) {
          data = response as HeroSlide[];
        } else if (
          response &&
          typeof response === 'object' &&
          'data' in response &&
          Array.isArray((response as { data: unknown }).data)
        ) {
          data = (response as { data: HeroSlide[] }).data;
        }

        if (!cancelled && data.length > 0) {
          setSlides(data);
          setIndex(0);
          setProgressKey((key) => key + 1);
        }
      } catch (error) {
        console.error('Error fetching hero slides:', error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    loadSlides();
    return () => {
      cancelled = true;
    };
  }, []);

  const slideCount = slides.length;
  const activeSlide = slides[index] ?? slides[0];
  const stats = Array.isArray(activeSlide?.stats) ? activeSlide.stats : [];

  const goTo = useCallback(
    (nextIndex: number) => {
      if (slideCount <= 1) return;
      const normalized = ((nextIndex % slideCount) + slideCount) % slideCount;
      let dir = normalized > index ? 1 : -1;
      if (index === slideCount - 1 && normalized === 0) dir = 1;
      if (index === 0 && normalized === slideCount - 1) dir = -1;
      setDirection(dir);
      setIndex(normalized);
      setProgressKey((key) => key + 1);
    },
    [index, slideCount]
  );

  const goNext = useCallback(() => goTo(index + 1), [goTo, index]);
  const goPrev = useCallback(() => goTo(index - 1), [goTo, index]);

  useEffect(() => {
    if (paused || reduceMotion || slideCount <= 1 || loading) return;
    const timer = window.setTimeout(goNext, AUTOPLAY_MS);
    return () => window.clearTimeout(timer);
  }, [goNext, index, loading, paused, progressKey, reduceMotion, slideCount]);

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'ArrowRight') goNext();
      if (event.key === 'ArrowLeft') goPrev();
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [goNext, goPrev]);

  return (
    <section
      id="home"
      className="hero-section relative overflow-hidden bg-navy-900"
      aria-roledescription="carousel"
      aria-label="Homepage hero"
      onMouseEnter={() => setHoverPaused(true)}
      onMouseLeave={() => setHoverPaused(false)}
    >
      {/* Full-width / full-height active image */}
      <div className="absolute inset-0">
        <AnimatePresence initial={false} custom={direction} mode="sync">
          <motion.div
            key={activeSlide?.id ?? index}
            className="absolute inset-0"
            custom={direction}
            initial={{
              opacity: reduceMotion ? 1 : 0,
              scale: reduceMotion ? 1 : 1.04,
            }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: reduceMotion ? 1 : 1.02 }}
            transition={{ duration: reduceMotion ? 0.15 : 0.75, ease: [0.22, 1, 0.36, 1] }}
          >
            <motion.div
              className="absolute inset-0"
              animate={reduceMotion ? undefined : { scale: [1, 1.06] }}
              transition={{ duration: AUTOPLAY_MS / 1000, ease: 'linear' }}
            >
              <SlidePhoto
                src={slideImage(activeSlide)}
                alt={activeSlide?.title || 'SSEOA hero'}
                priority={index === 0}
              />
            </motion.div>
          </motion.div>
        </AnimatePresence>

        <div className="absolute inset-0 bg-gradient-to-r from-navy-900/95 from-0% via-navy-900/55 via-40% to-navy-900/5 to-75%" />
        <div className="absolute inset-0 bg-gradient-to-t from-navy-900/75 via-navy-900/15 via-50% to-transparent" />
      </div>

      {/* Content */}
      <div className="relative z-10 flex h-full min-h-0 flex-col justify-between px-4 pb-6 pt-[5.25rem] sm:px-6 lg:px-8">
        <AnimatePresence mode="wait" custom={direction}>
          <motion.div
            key={`copy-${activeSlide?.id ?? index}`}
            custom={direction}
            initial={{ opacity: 0, y: reduceMotion ? 0 : 28 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: reduceMotion ? 0 : -16 }}
            transition={{ duration: reduceMotion ? 0.15 : 0.5, ease: [0.22, 1, 0.36, 1] }}
            className="mx-auto flex w-full max-w-7xl flex-1 flex-col justify-center"
            aria-live="polite"
          >
            <div className="max-w-2xl">
              {activeSlide?.badge ? (
                <span className="inline-flex rounded-full bg-primary-500 px-4 py-1.5 text-xs font-bold uppercase tracking-[0.14em] text-navy-900">
                  {activeSlide.badge}
                </span>
              ) : null}

              <div className="mt-4 sm:mt-5">
                <HighlightTitle title={activeSlide?.title || ''} />
              </div>

              {activeSlide?.subtitle ? (
                <p className="mt-4 max-w-xl text-sm leading-relaxed text-white/85 sm:text-base">
                  {activeSlide.subtitle}
                </p>
              ) : null}

              {(activeSlide?.primary_button_text || activeSlide?.secondary_button_text) && (
                <div className="mt-6 flex flex-wrap items-center gap-3">
                  {activeSlide.primary_button_text && activeSlide.primary_button_link ? (
                    <HeroCtaLink href={activeSlide.primary_button_link}>
                      <span className="inline-flex items-center gap-2 rounded-full bg-primary-500 px-5 py-2.5 text-sm font-bold text-navy-900 shadow-lg transition-transform hover:-translate-y-0.5 hover:bg-primary-400">
                        {activeSlide.primary_button_text}
                        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.25} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                        </svg>
                      </span>
                    </HeroCtaLink>
                  ) : null}

                  {activeSlide.secondary_button_text && activeSlide.secondary_button_link ? (
                    <HeroCtaLink href={activeSlide.secondary_button_link}>
                      <span className="inline-flex items-center rounded-full border border-white/60 px-5 py-2.5 text-sm font-bold text-white transition-colors hover:bg-white hover:text-navy-900">
                        {activeSlide.secondary_button_text}
                      </span>
                    </HeroCtaLink>
                  ) : null}
                </div>
              )}

              {stats.length > 0 ? (
                <div className="mt-8 flex max-w-xl flex-wrap gap-x-6 gap-y-3">
                  {stats.slice(0, 3).map((stat, statIndex) => (
                    <div key={`${stat.label}-${stat.value}`} className="flex min-w-0 items-center gap-2.5">
                      <span className="flex h-8 w-8 shrink-0 items-center justify-center text-primary-500">
                        <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                          {STAT_ICONS[statIndex % STAT_ICONS.length]}
                        </svg>
                      </span>
                      <div className="min-w-0">
                        <div className="text-sm font-black text-primary-500 sm:text-base">{stat.value}</div>
                        <div className="truncate text-[0.65rem] font-medium text-white/75 sm:text-xs">
                          {stat.label}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : null}
            </div>
          </motion.div>
        </AnimatePresence>

        {/* Thumbnail nav — smaller previews, bottom right */}
        {slideCount > 1 ? (
          <div className="relative mx-auto flex w-full max-w-7xl items-end justify-between gap-4">
            <div className="hidden sm:flex items-center gap-2">
              <button
                type="button"
                onClick={() => setUserPaused((v) => !v)}
                aria-pressed={userPaused}
                aria-label={userPaused ? 'Play slideshow' : 'Pause slideshow'}
                className="flex h-9 w-9 items-center justify-center rounded-full border border-white/25 text-white/80 transition-colors hover:border-primary-500 hover:text-primary-500"
              >
                {userPaused ? (
                  <svg className="h-3.5 w-3.5" fill="currentColor" viewBox="0 0 24 24" aria-hidden>
                    <path d="M8 5v14l11-7z" />
                  </svg>
                ) : (
                  <svg className="h-3.5 w-3.5" fill="currentColor" viewBox="0 0 24 24" aria-hidden>
                    <path d="M6 5h4v14H6zm8 0h4v14h-4z" />
                  </svg>
                )}
              </button>
              <span className="text-xs font-semibold tabular-nums text-white/50">
                {String(index + 1).padStart(2, '0')} / {String(slideCount).padStart(2, '0')}
              </span>
            </div>

            <div className="ml-auto flex items-center gap-2 sm:gap-3">
              <button
                type="button"
                onClick={goPrev}
                aria-label="Previous slide"
                className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-white/25 bg-navy-900/50 text-white backdrop-blur-sm transition-colors hover:bg-white hover:text-navy-900"
              >
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
              </button>

              <div className="flex items-end gap-2" role="tablist" aria-label="Hero slides">
                {slides.map((slide, slideIndex) => {
                  if (slideIndex === index) return null;

                  return (
                    <button
                      key={slide.id}
                      type="button"
                      role="tab"
                      aria-selected={false}
                      aria-label={`Go to slide: ${slide.title}`}
                      onClick={() => goTo(slideIndex)}
                      className="group relative h-12 w-[4.25rem] shrink-0 overflow-hidden rounded-lg border border-white/25 opacity-80 transition-all hover:border-primary-500/60 hover:opacity-100 sm:h-14 sm:w-24"
                    >
                      <SlidePhoto src={slideImage(slide)} alt="" className="object-cover object-center" />
                      <div className="absolute inset-0 bg-navy-900/35 transition-colors group-hover:bg-navy-900/15" />
                      <span className="absolute bottom-1 left-1.5 text-[9px] font-bold text-white/90 line-clamp-1 pr-1">
                        {slide.title}
                      </span>
                    </button>
                  );
                })}
              </div>

              <button
                type="button"
                onClick={goNext}
                aria-label="Next slide"
                className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary-500 text-navy-900 transition-colors hover:bg-primary-400"
              >
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </button>
            </div>

            {!reduceMotion ? (
              <div className="absolute -bottom-1 left-0 right-0 h-0.5 overflow-hidden rounded-full bg-white/10">
                <span
                  key={progressKey}
                  className="block h-full origin-left bg-primary-500"
                  style={{
                    animation: `hero-progress ${AUTOPLAY_MS}ms linear forwards`,
                    animationPlayState: paused ? 'paused' : 'running',
                  }}
                />
              </div>
            ) : null}
          </div>
        ) : null}
      </div>
    </section>
  );
};
