'use client';

import { useEffect, useState, type ReactElement } from 'react';
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';

const placeholderImages: Record<string, string> = {
  education: '/images/hero/slider-1.webp',
  'youth-support': '/images/hero/slider-2.webp',
  'food-security-agriculture': '/images/hero/slider-3.webp',
  default: '/images/hero/slider-1.webp',
};

interface Initiative {
  id: string;
  title: string;
  image: string;
  icon: ReactElement | null;
  stats: string;
  emoji: string;
}

function getPlaceholderImage(slug: string) {
  return placeholderImages[slug] || placeholderImages.default;
}

export function WhatWeDo() {
  const reduceMotion = useReducedMotion();
  const [initiatives, setInitiatives] = useState<Initiative[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchInitiatives();
  }, []);

  const fetchInitiatives = async () => {
    try {
      setLoading(true);
      setError(null);
      const response: unknown = await api.getThematicAreas();

      let areas: Record<string, unknown>[] = [];
      if (Array.isArray(response)) {
        areas = response;
      } else if (
        response &&
        typeof response === 'object' &&
        'data' in response &&
        Array.isArray((response as { data: unknown[] }).data)
      ) {
        areas = (response as { data: Record<string, unknown>[] }).data;
      }

      const mapped: Initiative[] = areas.map((area) => {
        let iconElement: ReactElement | null = null;
        if (area.icon && typeof area.icon === 'string') {
          iconElement = <div className="h-5 w-5" dangerouslySetInnerHTML={{ __html: area.icon }} />;
        }

        const slug = String(area.slug || area.id || '');
        const image =
          (area.image as string) ||
          (area.image_large as string) ||
          (area.image_medium as string) ||
          getPlaceholderImage(slug);

        return {
          id: slug,
          title: String(area.title || ''),
          image,
          icon: iconElement,
          stats: String(area.stats || ''),
          emoji: String(area.emoji || ''),
        };
      });

      setInitiatives(mapped);
      if (mapped.length === 0) setError('No initiatives found.');
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Failed to load initiatives';
      setError(message);
      setInitiatives([]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <section
      id="what-we-do"
      className="relative scroll-mt-[5.25rem] overflow-hidden bg-primary-50/40"
    >
      <div className="absolute inset-x-0 top-0 h-1.5 bg-primary-500" />
      <div className="pointer-events-none absolute -right-20 top-1/4 h-56 w-56 rounded-full bg-primary-500/8 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="What We Do"
            title={
              <>
                Our <TitleHighlight>Initiatives</TitleHighlight>
              </>
            }
            description="Education · Youth support · Agriculture & food security"
          />
        </motion.div>

        {error && !loading && (
          <div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-center text-sm text-red-700">
            {error}
            <button type="button" onClick={fetchInitiatives} className="ml-2 font-bold underline">
              Retry
            </button>
          </div>
        )}

        {loading ? (
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="aspect-[4/5] animate-pulse rounded-2xl bg-secondary-200 sm:aspect-[3/4]" />
            ))}
          </div>
        ) : initiatives.length > 0 ? (
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 lg:gap-5">
            {initiatives.map((item, index) => (
              <motion.div
                key={item.id}
                className="h-full"
                {...revealProps(reduceMotion, 0.06 + index * 0.08)}
              >
                <Link
                  href={`/programs/${item.id}`}
                  className="group relative flex aspect-[4/5] min-h-[16rem] overflow-hidden rounded-2xl border border-secondary-200 bg-white shadow-md transition-shadow duration-300 hover:shadow-xl sm:aspect-[3/4] sm:min-h-[18rem] lg:aspect-[4/5] lg:min-h-0"
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={item.image}
                    alt={item.title}
                    className="absolute inset-0 h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-navy-900/90 via-navy-900/35 to-navy-900/5" />

                  {(item.emoji || item.icon) && (
                    <span className="absolute left-4 top-4 flex h-10 w-10 items-center justify-center rounded-xl bg-primary-500 text-lg shadow-md">
                      {item.emoji || item.icon}
                    </span>
                  )}

                  <span className="absolute left-0 top-0 h-1 w-0 bg-primary-500 transition-all duration-500 group-hover:w-full" />

                  <div className="relative mt-auto flex w-full flex-col p-5">
                    <h3 className="text-lg font-black leading-tight text-white sm:text-xl">
                      {item.title}
                    </h3>
                    {item.stats ? (
                      <p className="mt-1.5 text-xs font-bold uppercase tracking-wide text-primary-400">
                        {item.stats}
                      </p>
                    ) : null}
                    <span className="mt-3 inline-flex items-center gap-1.5 text-sm font-bold text-white/90">
                      Explore programme
                      <span className="transition-transform duration-300 group-hover:translate-x-1">
                        →
                      </span>
                    </span>
                  </div>

                  <motion.div
                    className="pointer-events-none absolute inset-0 border-2 border-primary-500/0 transition-colors duration-300 group-hover:border-primary-500/50"
                    whileHover={reduceMotion ? undefined : { scale: 1.01 }}
                    transition={{ duration: 0.35, ease: easeOut }}
                  />
                </Link>
              </motion.div>
            ))}
          </div>
        ) : (
          !error && (
            <div className="flex items-center justify-center rounded-2xl border border-secondary-200 bg-secondary-50 py-12 text-neutral-500">
              No initiatives available.
            </div>
          )
        )}
      </div>
    </section>
  );
}
