'use client';

import { useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { motion, useReducedMotion } from 'motion/react';
import api from '@/lib/api';
import { easeOut, revealProps } from '@/lib/motion';
import { SectionHeader, TitleHighlight } from './SectionHeader';

type HomepageStory = {
  id: number;
  title: string;
  slug: string;
  excerpt?: string | null;
  category?: string | null;
  tags?: string[] | null;
  featured_image?: string | null;
  featured_image_large?: string | null;
  featured_image_medium?: string | null;
  thumbnail?: string | null;
};

type HomepageStoriesResponse = {
  featured: HomepageStory | null;
  latest: HomepageStory[];
};

const FALLBACK_FEATURED: HomepageStory = {
  id: 0,
  title: "Maryam's journey to education",
  slug: '',
  excerpt:
    '"I used to watch other children carrying books, and I wished I could be like them."',
  category: 'story',
  tags: ['Featured', 'CBE', 'Kunar'],
  featured_image: '/images/success-story-sseoa.jpg',
};

const FALLBACK_LATEST: HomepageStory[] = [
  {
    id: 1,
    title: 'Sema — A Light from a Remote Village',
    slug: '',
    category: 'Education',
    featured_image: '/images/hero/slider-2.webp',
  },
  {
    id: 2,
    title: "Halima Safi's New Beginning",
    slug: '',
    category: 'Teachers',
    featured_image: '/images/hero/slider-3.webp',
  },
];

function resolveImageUrl(story: HomepageStory): string {
  const candidate =
    story.featured_image_large ||
    story.featured_image_medium ||
    story.featured_image ||
    story.thumbnail;

  if (!candidate) return '/images/success-story-sseoa.jpg';
  if (candidate.startsWith('http') || candidate.startsWith('/')) return candidate;

  const base = process.env.NEXT_PUBLIC_API_URL?.replace('/api/v1', '') || 'http://localhost:8000';
  return `${base}${candidate.startsWith('/') ? candidate : `/${candidate}`}`;
}

function storyHref(story: HomepageStory): string {
  return story.slug ? `/blog/${story.slug}` : '/blog?category=story';
}

function formatTagLabel(tag: string): string {
  return tag
    .split('-')
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
}

function storyLabel(story: HomepageStory): string {
  if (story.tags?.length) {
    return formatTagLabel(story.tags[0]);
  }

  if (story.category && story.category !== 'story') {
    return story.category;
  }

  return 'Story';
}

function featuredBadge(story: HomepageStory): string {
  const labels = ['Featured'];

  if (story.tags?.length) {
    labels.push(...story.tags.slice(0, 2).map(formatTagLabel));
  } else if (story.category) {
    labels.push(storyLabel(story));
  }

  return labels.join(' · ');
}

export function FeaturedStory() {
  const reduceMotion = useReducedMotion();
  const [featured, setFeatured] = useState<HomepageStory>(FALLBACK_FEATURED);
  const [latestStories, setLatestStories] = useState<HomepageStory[]>(FALLBACK_LATEST);

  useEffect(() => {
    const fetchStories = async () => {
      try {
        const response: any = await api.getHomepageStories();
        const data: HomepageStoriesResponse = response?.data ?? response;

        if (data?.featured) {
          setFeatured(data.featured);
        }

        if (Array.isArray(data?.latest) && data.latest.length > 0) {
          setLatestStories(data.latest);
        }
      } catch (error) {
        console.error('Failed to load homepage stories:', error);
      }
    };

    fetchStories();
  }, []);

  const featuredImage = resolveImageUrl(featured);
  const isLocalhost =
    featuredImage.includes('localhost') || featuredImage.includes('127.0.0.1');

  return (
    <section
      id="success-stories"
      className="relative scroll-mt-[5.25rem] overflow-hidden bg-secondary-100"
    >
      <div className="pointer-events-none absolute -left-24 top-12 h-48 w-48 rounded-full bg-primary-500/12 blur-3xl" />
      <div className="pointer-events-none absolute -right-16 bottom-16 h-40 w-40 rounded-full bg-navy-800/6 blur-3xl" />

      <div className="relative mx-auto max-w-7xl px-4 py-10 sm:px-6 sm:py-14 lg:px-8 lg:py-16">
        <motion.div {...revealProps(reduceMotion)}>
          <SectionHeader
            spacing="compact"
            badge="Success Stories"
            title={
              <>
                A classroom, a book, <TitleHighlight>a future</TitleHighlight>
              </>
            }
          />
        </motion.div>

        <div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1.35fr)_minmax(0,0.65fr)] lg:items-stretch lg:gap-5">
          <motion.div
            className="group relative min-h-[16rem] overflow-hidden rounded-2xl bg-navy-800 shadow-lg sm:min-h-[20rem] lg:min-h-[24rem]"
            {...revealProps(reduceMotion, 0.06)}
          >
            <Link href={storyHref(featured)} className="absolute inset-0">
              <Image
                src={featuredImage}
                alt={featured.title}
                fill
                className="object-cover transition-transform duration-700 ease-out group-hover:scale-[1.03]"
                sizes="(max-width: 1024px) 100vw, 60vw"
                priority
                unoptimized={isLocalhost}
              />
              <div className="absolute inset-0 bg-gradient-to-t from-navy-900/80 via-navy-900/15 to-transparent" />
              <div className="absolute inset-x-0 bottom-0 p-4 sm:p-6">
                <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-primary-400">
                  {featuredBadge(featured)}
                </p>
                <h3 className="mt-1 text-xl font-black leading-tight text-white sm:text-2xl lg:text-3xl">
                  {featured.title}
                </h3>
              </div>
              <span className="absolute left-0 top-0 h-1 w-0 bg-primary-500 transition-all duration-500 group-hover:w-full" />
            </Link>
          </motion.div>

          <div className="flex min-h-0 flex-col gap-3">
            <motion.div
              className="flex flex-col justify-center rounded-2xl border border-secondary-200/80 bg-white p-4 shadow-sm sm:p-5 lg:flex-1"
              {...revealProps(reduceMotion, 0.1)}
            >
              {featured.excerpt && (
                <blockquote className="border-l-4 border-primary-500 pl-3">
                  <p className="text-sm leading-relaxed text-neutral-700">
                    {featured.excerpt}
                  </p>
                </blockquote>
              )}
              <Link
                href={storyHref(featured)}
                className="group/link mt-4 inline-flex w-fit items-center gap-1.5 rounded-full bg-navy-800 px-4 py-2 text-sm font-bold text-white transition-colors hover:bg-navy-700"
              >
                Read her story
                <span className="transition-transform duration-300 group-hover/link:translate-x-1">
                  →
                </span>
              </Link>
            </motion.div>

            <motion.div
              className="grid grid-cols-1 gap-3 sm:grid-cols-2"
              {...revealProps(reduceMotion, 0.14)}
            >
              {latestStories.map((story) => {
                const storyImage = resolveImageUrl(story);
                const storyIsLocalhost =
                  storyImage.includes('localhost') || storyImage.includes('127.0.0.1');

                return (
                  <motion.article
                    key={story.id}
                    className="min-h-0"
                    whileHover={reduceMotion ? undefined : { y: -2 }}
                    transition={{ duration: 0.3, ease: easeOut }}
                  >
                    <Link
                      href={storyHref(story)}
                      className="group relative flex aspect-[16/11] min-h-[8rem] overflow-hidden rounded-xl bg-navy-800 shadow-md"
                    >
                      <Image
                        src={storyImage}
                        alt={story.title}
                        fill
                        className="object-cover transition-transform duration-700 group-hover:scale-110"
                        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 45vw, 20vw"
                        unoptimized={storyIsLocalhost}
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-navy-900/90 via-navy-900/40 to-navy-900/10" />
                      <div className="relative mt-auto p-3 sm:p-3.5">
                        <p className="text-[9px] font-bold uppercase tracking-[0.14em] text-primary-400">
                          {storyLabel(story)}
                        </p>
                        <h3 className="mt-0.5 line-clamp-2 text-sm font-bold leading-snug text-white">
                          {story.title}
                        </h3>
                      </div>
                      <span className="absolute bottom-0 left-0 h-0.5 w-0 bg-primary-500 transition-all duration-500 group-hover:w-full" />
                    </Link>
                  </motion.article>
                );
              })}
            </motion.div>

            <Link
              href="/blog?category=story"
              className="group/all inline-flex w-full items-center justify-center gap-1.5 rounded-xl border border-secondary-200 bg-white py-2.5 text-sm font-bold text-navy-800 shadow-sm transition-all hover:border-primary-500/50 hover:bg-primary-50/50"
            >
              All stories
              <span className="transition-transform duration-300 group-hover/all:translate-x-1">
                →
              </span>
            </Link>
          </div>
        </div>
      </div>
    </section>
  );
}
