'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { motion, useReducedMotion } from 'motion/react';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import api from '@/lib/api';

interface MessageFromDirector {
  id: number;
  director_name: string;
  director_position: string;
  director_bio: string;
  message_title: string;
  message_content: string;
  signature_text: string;
  stats: Record<string, string>;
  email: string;
  image: string;
  image_thumb?: string;
  image_medium?: string;
  image_large?: string;
}

const ease = [0.22, 1, 0.36, 1] as const;

function initialsFromName(name: string) {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? '')
    .join('');
}

export default function MessageFromDirectorPage() {
  const reduceMotion = useReducedMotion();
  const [messageFromDirector, setMessageFromDirector] = useState<MessageFromDirector | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const fetchMessage = async () => {
    try {
      setLoading(true);
      setError(null);

      const response: any = await api.getMessageFromDirector();
      if (response) {
        setMessageFromDirector(response);
      }
    } catch (err: any) {
      console.error('Error fetching message from director:', err);
      setError(err?.message || 'Failed to load message from director');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="flex min-h-[70vh] items-center justify-center px-4">
          <div className="text-center">
            <div className="mb-4 inline-block h-12 w-12 animate-spin rounded-full border-b-2 border-primary-500" />
            <p className="text-lg text-neutral-600">Loading message from the director…</p>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  if (error || !messageFromDirector) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="flex min-h-[70vh] items-center justify-center px-4">
          <div className="text-center">
            <p className="mb-4 text-xl text-neutral-800">{error || 'Message not found'}</p>
            <button
              onClick={fetchMessage}
              className="inline-flex cursor-pointer items-center rounded-lg bg-navy-800 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-navy-700"
            >
              Try again
            </button>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  const directorImage =
    messageFromDirector.image_large ||
    messageFromDirector.image_medium ||
    messageFromDirector.image ||
    '';
  const stats = messageFromDirector.stats || {};

  return (
    <div className="min-h-screen overflow-x-hidden bg-white">
      <Header />

      <section className="relative overflow-hidden border-b border-secondary-200 bg-white pt-28 pb-12 sm:pt-32 sm:pb-16">
        <div className="pointer-events-none absolute -left-24 top-10 h-64 w-64 rounded-full bg-primary-500/10 blur-3xl" />
        <div className="pointer-events-none absolute -right-16 bottom-0 h-56 w-56 rounded-full bg-navy-800/5 blur-3xl" />

        <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <motion.span
            className="inline-flex items-center gap-2 rounded-full border border-primary-500/30 bg-primary-500/10 px-4 py-1.5 text-xs font-bold uppercase tracking-widest text-primary-700"
            initial={reduceMotion ? false : { opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, ease }}
          >
            <span className="h-1.5 w-1.5 rounded-full bg-primary-500" />
            Leadership
          </motion.span>

          <motion.h1
            className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl"
            initial={reduceMotion ? false : { opacity: 0, y: 22 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.08, ease }}
          >
            Message from the{' '}
            <span className="relative inline-block text-primary-600">
              Director
              <motion.svg
                className="absolute -bottom-2 left-0 w-full text-primary-400"
                viewBox="0 0 180 12"
                preserveAspectRatio="none"
                aria-hidden
                initial={reduceMotion ? false : { pathLength: 0, opacity: 0 }}
                animate={{ pathLength: 1, opacity: 1 }}
                transition={{ duration: 0.8, delay: 0.45, ease }}
              >
                <motion.path
                  d="M2 9C40 2 140 2 178 9"
                  stroke="currentColor"
                  strokeWidth="4"
                  strokeLinecap="round"
                  fill="none"
                  initial={reduceMotion ? false : { pathLength: 0 }}
                  animate={{ pathLength: 1 }}
                  transition={{ duration: 0.8, delay: 0.45, ease }}
                />
              </motion.svg>
            </span>
          </motion.h1>

          <motion.p
            className="mt-6 max-w-2xl text-lg leading-relaxed text-neutral-600"
            initial={reduceMotion ? false : { opacity: 0, y: 18 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.55, delay: 0.18, ease }}
          >
            {messageFromDirector.message_title ||
              'A word from our Executive Director on education, livelihoods, and the communities we serve.'}
          </motion.p>
        </div>
      </section>

      <section className="relative overflow-hidden bg-white py-12 md:py-20">
        <div className="pointer-events-none absolute -right-20 top-10 h-72 w-72 rounded-full bg-primary-500/10 blur-3xl" />
        <div className="pointer-events-none absolute -left-16 bottom-0 h-64 w-64 rounded-full bg-navy-800/5 blur-3xl" />

        <div className="relative mx-auto grid max-w-7xl grid-cols-1 gap-10 px-4 sm:px-6 lg:grid-cols-12 lg:gap-14 lg:px-8">
          <motion.aside
            className="lg:col-span-4"
            initial={reduceMotion ? false : { opacity: 0, y: 24 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-80px' }}
            transition={{ duration: 0.65, ease }}
          >
            <div className="overflow-hidden rounded-3xl border border-secondary-200 bg-secondary-50 lg:sticky lg:top-24">
              <div className="relative aspect-[4/5] overflow-hidden bg-navy-800">
                {directorImage ? (
                  <img
                    src={directorImage}
                    alt={messageFromDirector.director_name}
                    className="h-full w-full object-cover object-top"
                  />
                ) : (
                  <div className="flex h-full flex-col items-center justify-center bg-navy-800 px-6 text-center">
                    <span className="flex h-24 w-24 items-center justify-center rounded-full bg-primary-500 text-3xl font-black text-navy-800">
                      {initialsFromName(messageFromDirector.director_name)}
                    </span>
                    <p className="mt-6 text-xs font-bold uppercase tracking-widest text-primary-400">
                      Executive Director
                    </p>
                  </div>
                )}
              </div>

              <div className="p-6 sm:p-8">
                <h2 className="text-2xl font-black text-neutral-900">{messageFromDirector.director_name}</h2>
                <p className="mt-1 text-sm font-semibold text-primary-600">
                  {messageFromDirector.director_position}
                </p>
                {messageFromDirector.director_bio && (
                  <p className="mt-4 text-sm leading-relaxed text-neutral-600">
                    {messageFromDirector.director_bio}
                  </p>
                )}
                {messageFromDirector.email && (
                  <a
                    href={`mailto:${messageFromDirector.email}`}
                    className="mt-4 inline-block cursor-pointer text-sm font-semibold text-navy-800 hover:text-primary-600"
                  >
                    {messageFromDirector.email}
                  </a>
                )}
              </div>
            </div>
          </motion.aside>

          <div className="lg:col-span-8">
            <motion.div
              className="rounded-3xl border border-secondary-200 bg-white p-6 sm:p-8 md:p-10"
              initial={reduceMotion ? false : { opacity: 0, y: 24 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true, margin: '-80px' }}
              transition={{ duration: 0.65, delay: 0.08, ease }}
            >
              <div
                className="prose prose-lg max-w-none text-neutral-700 [&>p]:mb-5 [&>p]:leading-relaxed [&>p:last-child]:mb-0"
                dangerouslySetInnerHTML={{ __html: messageFromDirector.message_content }}
              />

              {messageFromDirector.signature_text && (
                <div className="mt-10 border-t border-secondary-200 pt-8">
                  <p className="text-sm font-bold uppercase tracking-widest text-primary-600">
                    With gratitude and commitment
                  </p>
                  <p className="mt-3 text-2xl font-black text-neutral-900">
                    {messageFromDirector.signature_text}
                  </p>
                  <p className="mt-1 text-sm font-semibold text-neutral-500">
                    {messageFromDirector.director_position}, SSEOA
                  </p>
                </div>
              )}
            </motion.div>
          </div>
        </div>
      </section>

      {Object.keys(stats).length > 0 && (
        <section className="relative overflow-hidden bg-secondary-50 py-12 sm:py-16">
          <div className="pointer-events-none absolute inset-x-0 top-0 h-1.5 bg-primary-500" />
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <p className="text-xs font-bold uppercase tracking-widest text-primary-600">Our impact</p>
            <h2 className="mt-3 text-3xl font-black text-neutral-900 sm:text-4xl">By the numbers</h2>
            <div className="mt-8 grid grid-cols-2 gap-4 md:grid-cols-4">
              {Object.entries(stats).map(([label, value]) => (
                <div
                  key={label}
                  className="rounded-2xl border border-secondary-200 bg-white px-5 py-6"
                >
                  <p className="text-2xl font-black text-navy-800 sm:text-3xl">{value}</p>
                  <p className="mt-2 text-sm font-semibold text-neutral-500">{label}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      <section className="bg-white py-16 sm:py-20">
        <div className="mx-auto max-w-3xl px-4 text-center sm:px-6 lg:px-8">
          <h3 className="text-3xl font-black text-neutral-900 sm:text-4xl">Want to work with us?</h3>
          <p className="mx-auto mt-4 max-w-xl text-lg leading-relaxed text-neutral-600">
            Partnerships, programmes, or questions about SSEOA — we would like to hear from you.
          </p>
          <div className="mt-8 flex flex-col items-center justify-center gap-3 sm:flex-row">
            {messageFromDirector.email && (
              <a
                href={`mailto:${messageFromDirector.email}`}
                className="inline-flex cursor-pointer items-center justify-center rounded-lg bg-navy-800 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-navy-700"
              >
                Email {messageFromDirector.email}
              </a>
            )}
            <Link
              href="/contact-us"
              className="inline-flex cursor-pointer items-center justify-center rounded-lg border border-secondary-300 bg-white px-6 py-3 text-sm font-bold text-navy-800 transition-colors hover:border-primary-500 hover:text-primary-600"
            >
              Contact form
            </Link>
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}
