"use client";

import { useState, useEffect, useRef } from "react";
import { ArrowRight, Target, Eye, Award, Users, BookOpen, TrendingUp, Heart, Shield, Lightbulb, Handshake, Zap, CheckCircle2, ChevronLeft, ChevronRight, Leaf } from "lucide-react";
import { EditableSection } from "@/components/admin/EditableSection";
import { useEditMode } from "@/context/EditModeContext";

const DOMAIN_ICONS = [Heart, Leaf, BookOpen, Users, Lightbulb, Shield, TrendingUp, Award];
const VALUE_ICONS = [Award, Lightbulb, Shield, Handshake];

type MissionContent = {
  pageTitle: string;
  pageSubtitle: string;
  heroImage: string;
  stat1Value: string; stat1Label: string;
  stat2Value: string; stat2Label: string;
  stat3Value: string; stat3Label: string;
  stat4Value: string; stat4Label: string;
  missionTitle: string;
  missionText: string;
  visionTitle: string;
  visionText: string;
  valuesTitle: string;
  domainsTitle: string;
  domainsSubtitle: string;
  timelineTitle: string;
  ctaTitle: string;
  ctaDescription: string;
};

type CoreValue = {
  id: string;
  number: string;
  name: string;
  description: string;
  color: string;
  order: number;
};

type Domain = {
  id: string;
  name: string;
  description: string;
  color: string;
  order: number;
};

type TimelineEvent = {
  id: string;
  year: string;
  text: string;
  order: number;
};

const CONTENT_DEFAULTS: MissionContent = {
  pageTitle: "Mission & Vision",
  pageSubtitle: "Depuis 2002, ANED s'engage pour que chaque enfant, chaque femme et chaque ménage mauritanien sécurise durablement sa situation alimentaire et nutritionnelle.",
  heroImage: "/mission&vision.jpg",
  stat1Value: "20+", stat1Label: "Années d'expérience",
  stat2Value: "7", stat2Label: "Domaines d'expertise",
  stat3Value: "50K+", stat3Label: "Bénéficiaires",
  stat4Value: "15+", stat4Label: "Projets réalisés",
  missionTitle: "Notre Mission",
  missionText: "Combattre la malnutrition et l'insécurité alimentaire, particulièrement chez les enfants de moins de 5 ans et les femmes vulnérables, à travers des interventions innovantes, communautaires et durables en Mauritanie.",
  visionTitle: "Notre Vision",
  visionText: "Une Mauritanie où aucun enfant ne souffre de malnutrition, où chaque ménage a accès à une alimentation saine et suffisante, et où les communautés sont résilientes face aux crises alimentaires.",
  valuesTitle: "Nos valeurs fondamentales",
  domainsTitle: "Domaines d'expertise",
  domainsSubtitle: "Six domaines d'intervention pour une action globale et efficace contre la malnutrition.",
  timelineTitle: "20+ ans d'engagement",
  ctaTitle: "Rejoignez notre combat",
  ctaDescription: "Partenaires, bénévoles, chercheurs — ensemble, nous pouvons nourrir chaque enfant de Mauritanie et bâtir un avenir sans malnutrition.",
};

const STAT_ICONS = [Award, Zap, Users, CheckCircle2];

export default function MissionPage() {
  const timelineRef = useRef<HTMLDivElement>(null);
  const [content, setContent] = useState<MissionContent>(CONTENT_DEFAULTS);
  const [coreValues, setCoreValues] = useState<CoreValue[]>([]);
  const [domains, setDomains] = useState<Domain[]>([]);
  const [timeline, setTimeline] = useState<TimelineEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const { contentVersion } = useEditMode();

  useEffect(() => {
    setLoading(true);
    Promise.all([
      fetch("/api/mission-content").then((r) => r.json()),
      fetch("/api/core-values").then((r) => r.json()),
      fetch("/api/domains").then((r) => r.json()),
      fetch("/api/timeline").then((r) => r.json()),
    ])
      .then(([c, v, d, t]) => {
        setContent({ ...CONTENT_DEFAULTS, ...c });
        setCoreValues(v);
        setDomains(d);
        setTimeline(t);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [contentVersion]);

  const scrollTimeline = (direction: "left" | "right") => {
    if (timelineRef.current) {
      timelineRef.current.scrollBy({ left: direction === "left" ? -400 : 400, behavior: "smooth" });
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-10 h-10 border-4 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin" />
      </div>
    );
  }

  const stats = [
    { value: content.stat1Value, label: content.stat1Label },
    { value: content.stat2Value, label: content.stat2Label },
    { value: content.stat3Value, label: content.stat3Label },
    { value: content.stat4Value, label: content.stat4Label },
  ];

  return (
    <>
      {/* Page Hero */}
      <EditableSection sectionId="mission-hero" label="En-tête de la page Mission">
        <section className="relative bg-linear-to-br from-[#F7F8F5] via-white to-[#E8F5E9] overflow-hidden">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
            <div className="py-20 sm:py-28 px-4 sm:px-6 lg:px-8 lg:pl-16 relative z-10">
              <div className="absolute inset-0 opacity-[0.03]">
                <div className="absolute inset-0" style={{ backgroundImage: `radial-gradient(circle at 2px 2px, #4A7C59 1px, transparent 0)`, backgroundSize: "32px 32px" }} />
              </div>
              <div className="absolute top-10 left-10 w-64 h-64 bg-[#4A7C59]/5 rounded-full blur-3xl" />
              <div className="absolute bottom-10 right-10 w-96 h-96 bg-[#E67E22]/5 rounded-full blur-3xl" />

              <div className="relative z-10">
                <div className="flex items-center gap-2 mb-6">
                  <div className="w-12 h-12 bg-[#4A7C59]/10 rounded-xl flex items-center justify-center">
                    <Target size={24} className="text-[#4A7C59]" />
                  </div>
                  <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest">À propos d&apos;ANED</p>
                </div>
                <h1 className="font-serif text-4xl sm:text-5xl lg:text-6xl font-black text-[#2C3E50] leading-tight mb-6">{content.pageTitle}</h1>
                <p className="text-lg sm:text-xl text-gray-600 leading-relaxed">{content.pageSubtitle}</p>
              </div>
            </div>

            <div className="relative h-[400px] lg:h-full min-h-[500px]">
              <div className="absolute inset-0">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={content.heroImage} alt="Bénévoles ANED en action" className="w-full h-full object-cover" />
                <div className="absolute inset-0 bg-gradient-to-r from-[#F7F8F5]/20 to-transparent lg:from-[#F7F8F5]/40" />
              </div>
            </div>
          </div>
        </section>
      </EditableSection>

      {/* Stats */}
      <EditableSection sectionId="mission-stats" label="Statistiques Mission">
        <section className="py-12 bg-white border-b border-gray-100">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {stats.map((stat, i) => {
                const Icon = STAT_ICONS[i] ?? Award;
                return (
                  <div key={stat.label} className="text-center group">
                    <div className="inline-flex items-center justify-center w-14 h-14 bg-[#4A7C59]/10 rounded-xl mb-4 group-hover:bg-[#4A7C59]/20 transition-colors">
                      <Icon size={24} className="text-[#4A7C59]" />
                    </div>
                    <div className="font-serif text-3xl sm:text-4xl font-black text-[#2C3E50] mb-2">{stat.value}</div>
                    <div className="text-sm text-gray-600">{stat.label}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </section>
      </EditableSection>

      {/* Mission & Vision Cards */}
      <EditableSection sectionId="mission-vision" label="Textes Mission & Vision">
        <section className="py-20 sm:py-24 bg-white">
          <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div className="group relative bg-linear-to-br from-[#F7F8F5] to-white rounded-3xl p-10 border-2 border-gray-100 hover:border-[#4A7C59]/30 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02]">
                <div className="absolute top-0 right-0 w-32 h-32 bg-[#4A7C59]/5 rounded-full blur-2xl group-hover:bg-[#4A7C59]/10 transition-all" />
                <div className="relative">
                  <div className="w-16 h-16 bg-linear-to-br from-[#4A7C59] to-[#3d6849] rounded-2xl flex items-center justify-center mb-6 shadow-lg group-hover:scale-110 transition-transform">
                    <Target size={28} className="text-white" />
                  </div>
                  <h2 className="font-serif text-3xl font-black text-[#2C3E50] mb-5">{content.missionTitle}</h2>
                  <p className="text-gray-600 leading-relaxed text-base">{content.missionText}</p>
                </div>
              </div>

              <div className="group relative bg-linear-to-br from-[#2C3E50] via-[#34495e] to-[#2C3E50] rounded-3xl p-10 border-2 border-[#2C3E50] hover:border-[#4A7C59] transition-all duration-300 hover:shadow-2xl hover:scale-[1.02] overflow-hidden">
                <div className="absolute top-0 right-0 w-32 h-32 bg-white/5 rounded-full blur-2xl group-hover:bg-white/10 transition-all" />
                <div className="absolute -bottom-10 -left-10 w-40 h-40 bg-[#4A7C59]/10 rounded-full blur-3xl" />
                <div className="relative">
                  <div className="w-16 h-16 bg-linear-to-br from-[#4A7C59] to-[#27AE60] rounded-2xl flex items-center justify-center mb-6 shadow-lg group-hover:scale-110 transition-transform">
                    <Eye size={28} className="text-white" />
                  </div>
                  <h2 className="font-serif text-3xl font-black text-white mb-5">{content.visionTitle}</h2>
                  <p className="text-white/90 leading-relaxed text-base">{content.visionText}</p>
                </div>
              </div>
            </div>
          </div>
        </section>
      </EditableSection>

      {/* Core Values */}
      <section className="py-20 sm:py-24 bg-gradient-to-b from-[#F7F8F5] to-white relative overflow-hidden">
        <div className="absolute top-20 right-0 w-64 h-64 bg-[#E67E22]/5 rounded-full blur-3xl" />
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
          <div className="text-center mb-12">
            <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest mb-3">Ce qui nous guide</p>
            <h2 className="font-serif text-3xl sm:text-5xl font-black text-[#2C3E50] mb-4">{content.valuesTitle}</h2>
            <p className="text-gray-500 max-w-2xl mx-auto">Quatre piliers qui définissent notre approche et guident chacune de nos actions sur le terrain.</p>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            {coreValues.map((v, i) => {
              const Icon = VALUE_ICONS[i % VALUE_ICONS.length];
              return (
                <EditableSection key={v.id} sectionId={`value-${v.id}`} label={`Valeur : ${v.name}`}>
                  <div
                    className="group relative bg-white rounded-2xl p-8 border-2 transition-all duration-300 hover:shadow-xl hover:scale-[1.02] overflow-hidden"
                    style={{ borderColor: `${v.color}15` }}
                  >
                    <div className="absolute inset-0 opacity-0 group-hover:opacity-5 transition-opacity duration-300" style={{ background: `linear-gradient(135deg, ${v.color}, transparent)` }} />
                    <div className="relative flex gap-6">
                      <div className="flex-shrink-0">
                        <span className="font-serif text-6xl sm:text-7xl font-black leading-none opacity-15 group-hover:opacity-25 transition-opacity" style={{ color: v.color }}>
                          {v.number}
                        </span>
                      </div>
                      <div className="flex-1">
                        <div className="w-12 h-12 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform" style={{ backgroundColor: `${v.color}15` }}>
                          <Icon size={24} style={{ color: v.color }} />
                        </div>
                        <h3 className="font-bold text-xl mb-3" style={{ color: v.color }}>{v.name}</h3>
                        <p className="text-sm text-gray-700 leading-relaxed font-medium">{v.description}</p>
                      </div>
                    </div>
                  </div>
                </EditableSection>
              );
            })}
          </div>
        </div>
      </section>

      {/* Domains */}
      <section className="py-20 sm:py-24 bg-white">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-14">
            <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest mb-3">Ce que nous faisons</p>
            <h2 className="font-serif text-3xl sm:text-5xl font-black text-[#2C3E50] mb-4">{content.domainsTitle}</h2>
            <p className="text-gray-600 max-w-2xl mx-auto">{content.domainsSubtitle}</p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {domains.map((d, i) => {
              const Icon = DOMAIN_ICONS[i % DOMAIN_ICONS.length];
              return (
                <EditableSection key={d.id} sectionId={`domain-${d.id}`} label={`Domaine : ${d.name}`}>
                  <div className="bg-white border border-gray-200 rounded-xl p-6 hover:shadow-lg transition-shadow h-full">
                    <div className="flex items-center gap-4 mb-4">
                      <div className="w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0" style={{ backgroundColor: `${d.color}15` }}>
                        <Icon size={22} style={{ color: d.color }} />
                      </div>
                      <h3 className="font-bold text-base text-[#2C3E50]">{d.name}</h3>
                    </div>
                    <p className="text-sm text-gray-700 leading-relaxed">{d.description}</p>
                  </div>
                </EditableSection>
              );
            })}
          </div>
        </div>
      </section>

      {/* Timeline */}
      <section className="py-16 bg-linear-to-br from-[#F7F8F5] to-white relative overflow-hidden">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between mb-8">
            <div>
              <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest mb-2">Notre parcours</p>
              <h2 className="font-serif text-3xl sm:text-4xl font-black text-[#2C3E50]">{content.timelineTitle}</h2>
            </div>
            <div className="flex gap-2">
              <button onClick={() => scrollTimeline("left")} className="w-10 h-10 rounded-lg bg-white border border-gray-200 hover:border-[#4A7C59] hover:bg-[#4A7C59] hover:text-white transition-all shadow-sm flex items-center justify-center" aria-label="Précédent">
                <ChevronLeft size={18} />
              </button>
              <button onClick={() => scrollTimeline("right")} className="w-10 h-10 rounded-lg bg-white border border-gray-200 hover:border-[#4A7C59] hover:bg-[#4A7C59] hover:text-white transition-all shadow-sm flex items-center justify-center" aria-label="Suivant">
                <ChevronRight size={18} />
              </button>
            </div>
          </div>

          <div className="relative pt-4">
            <div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-[#4A7C59]/20 via-[#4A7C59] to-[#4A7C59]/20" />
            <div ref={timelineRef} className="flex gap-6 overflow-x-auto pb-8" style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}>
              {timeline.map((item) => (
                <EditableSection key={item.id} sectionId={`timeline-${item.id}`} label={`Événement ${item.year}`} className="flex-shrink-0 w-[280px] h-[200px]">
                  <div className="bg-white rounded-xl border border-gray-200 hover:border-[#4A7C59]/50 shadow-sm hover:shadow-md transition-all p-5 h-full flex flex-col">
                    <div className="inline-flex items-center justify-center px-4 py-2 bg-gradient-to-r from-[#4A7C59] to-[#27AE60] rounded-lg mb-4 flex-shrink-0">
                      <span className="font-serif text-xl font-black text-white">{item.year}</span>
                    </div>
                    <p className="text-sm text-gray-700 leading-relaxed flex-1">{item.text}</p>
                  </div>
                </EditableSection>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* CTA */}
      <EditableSection sectionId="mission-cta" label="Appel à l'action Mission">
        <section className="relative py-24 sm:py-32 overflow-hidden">
          <div className="absolute inset-0">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/cta-mission.jpeg" alt="ANED en action" className="w-full h-full object-cover" />
            <div className="absolute inset-0 bg-gradient-to-r from-[#2C3E50]/95 via-[#2C3E50]/90 to-[#2C3E50]/80" />
            <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent" />
          </div>
          <div className="absolute inset-0 opacity-5">
            <div className="absolute inset-0" style={{ backgroundImage: `radial-gradient(circle at 2px 2px, white 1px, transparent 0)`, backgroundSize: "40px 40px" }} />
          </div>

          <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10 text-center">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-[#4A7C59]/20 backdrop-blur-sm rounded-2xl mb-6 ring-4 ring-white/10">
              <Handshake size={32} className="text-[#4A7C59]" />
            </div>
            <h2 className="font-serif text-3xl sm:text-5xl lg:text-6xl font-black text-white mb-5 leading-tight">{content.ctaTitle}</h2>
            <p className="text-white/80 text-lg mb-8 leading-relaxed max-w-2xl mx-auto">{content.ctaDescription}</p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <a href="/contact" className="group bg-gradient-to-r from-[#4A7C59] to-[#27AE60] hover:from-[#27AE60] hover:to-[#4A7C59] text-white px-8 py-4 rounded-xl font-semibold transition-all flex items-center justify-center gap-2 text-base shadow-2xl hover:shadow-[#4A7C59]/50 hover:scale-105">
                Nous contacter <ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
              </a>
              <a href="/projets" className="group border-2 border-white/30 hover:border-white hover:bg-white/10 text-white px-8 py-4 rounded-xl font-semibold transition-all text-base flex items-center justify-center gap-2 backdrop-blur-sm hover:scale-105">
                Nos projets <ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
              </a>
            </div>
          </div>
          <div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-[#4A7C59] via-[#E67E22] to-[#4A7C59]" />
        </section>
      </EditableSection>
    </>
  );
}
