import { Link, router } from '@inertiajs/react';
import { SeoHead } from '@/components/seo-head';
import { motion } from 'framer-motion';
import { ArrowRight, BookOpen, ExternalLink, FileText, Presentation, SquareArrowOutUpRight } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import PublicLayout from '@/layouts/public-layout';

interface Publication {
    id: number;
    title: string;
    authors: string;
    abstract: string;
    journal: string | null;
    year: number;
    doi: string | null;
    url: string | null;
    type: string;
    tags: string[] | null;
    is_published: boolean;
}

interface Stats {
    total: number;
    journal_articles: number;
    conference: number;
    book_chapters: number;
}

interface Filters {
    year: string | null;
    type: string | null;
}

interface Initiative { id: number; title: string; summary: string | null; cover_url: string | null; url: string | null }

interface Props {
    publications: Publication[];
    filters: Filters;
    stats: Stats;
    initiatives: Initiative[];
}

const typeIcons: Record<string, typeof BookOpen> = {
    journal_article: BookOpen,
    conference_paper: Presentation,
    book_chapter: FileText,
};

const typeLabel: Record<string, string> = {
    journal_article: 'Journal Article',
    conference_paper: 'Conference Paper',
    book_chapter: 'Book Chapter',
};

// Left border accent colour per publication type
const typeAccent: Record<string, string> = {
    journal_article: 'border-l-[#1b265c]',
    conference_paper: 'border-l-[#df2548]',
    book_chapter: 'border-l-[#D4A843]',
};

function useInView(threshold = 0.1) {
    const ref = useRef<HTMLDivElement>(null);
    const [inView, setInView] = useState(false);
    useEffect(() => {
        const observer = new IntersectionObserver(
            ([e]) => {
                if (e.isIntersecting) {
                    setInView(true);
                    observer.disconnect();
                }
            },
            { threshold },
        );
        if (ref.current) observer.observe(ref.current);
        return () => observer.disconnect();
    }, [threshold]);
    return { ref, inView };
}

function setFilter(filters: Filters, key: string, value: string | null) {
    router.get('/research', { ...filters, [key]: value ?? undefined }, { preserveState: true, replace: true });
}

export default function Research({ publications, filters, stats, initiatives }: Props) {
    const years = [...new Set(publications.map((p) => p.year))].sort((a, b) => b - a);
    const initiativesSection = useInView();

    return (
        <div>
            <SeoHead
                title="Research & Publications — ABEC Africa"
                description="Browse peer-reviewed publications, conference papers, and book chapters from ABEC Africa member institutions. Explore our research spin-offs driving biomedical innovation across the continent."
                image="/images/scientist-microscope-warmlight.jpg"
                keywords="ABEC Africa research, African biomedical engineering publications, biomedical research Africa, biomedical engineering journal articles Africa, ABEC publications"
                url="https://abecafrica.org/research"
                jsonLd={{
                    '@context': 'https://schema.org',
                    '@type': 'CollectionPage',
                    url: 'https://abecafrica.org/research',
                    name: 'Research & Publications — ABEC Africa',
                    description: 'Peer-reviewed publications and research initiatives from ABEC Africa member institutions.',
                    isPartOf: { '@id': 'https://abecafrica.org/#website' },
                    inLanguage: 'en-GB',
                }}
            />
            {/* HERO */}
            <section className="relative min-h-[65vh] flex items-end overflow-hidden">
                <div className="absolute inset-0">
                    <img
                        src="/images/scientist-microscope-bluelight.jpg"
                        alt="Scientist at microscope in blue lab light"
                        className="w-full h-full object-cover object-center"
                    />
                    <div
                        className="absolute inset-0"
                        style={{
                            background:
                                'linear-gradient(to top, rgba(17,17,19,0.97) 0%, rgba(27,38,92,0.65) 45%, rgba(27,38,92,0.2) 80%, transparent 100%)',
                        }}
                    />
                </div>
                <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 pt-48 w-full">
                    <motion.div initial={{ opacity: 0, y: 24 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.7 }}>
                        <div className="flex items-center gap-3 mb-4">
                            <div className="w-8 h-px bg-[#d0d4ec]/60" />
                            <span className="text-[#d0d4ec]/70 text-xs tracking-[0.2em] uppercase font-semibold">Knowledge Production</span>
                        </div>
                        <h1 className="text-5xl lg:text-7xl font-black text-white tracking-tight leading-tight mb-4">
                            Research &amp;
                            <br />
                            Publications
                        </h1>
                        <p className="text-white/60 text-lg max-w-xl leading-relaxed">
                            ABEC promotes high-impact research in biomedical engineering education, innovation, and healthcare technology design
                            across Africa.
                        </p>
                    </motion.div>
                </div>
            </section>

            {/* OUR CONTRIBUTION — redesigned with stats */}
            <section className="bg-white">
                <div className="grid lg:grid-cols-2">
                    {/* Image */}
                    <div className="relative h-72 lg:h-auto min-h-[380px] overflow-hidden">
                        <img
                            src="/images/student-studying-archive.jpg"
                            alt="Student studying in archive library"
                            className="w-full h-full object-cover"
                        />
                        <div
                            className="absolute inset-0"
                            style={{ background: 'linear-gradient(to right, transparent 40%, white 100%)' }}
                        />
                    </div>

                    {/* Content */}
                    <div className="flex flex-col justify-center py-16 px-8 lg:px-14">
                        <div className="section-rule" />
                        <span className="label-caps block mb-4">Our Contribution</span>
                        <h2 className="text-3xl font-black text-[#1b265c] tracking-tight mb-8">Advancing the Field</h2>

                        {/* Stat tiles */}
                        <div className="grid grid-cols-2 sm:grid-cols-4 gap-px bg-[#d0d4ec] mb-8">
                            {[
                                { value: stats.total,            label: 'Publications' },
                                { value: stats.journal_articles, label: 'Journal Articles' },
                                { value: stats.conference,       label: 'Conference Papers' },
                                { value: stats.book_chapters,    label: 'Book Chapters' },
                            ].map((s) => (
                                <div key={s.label} className="bg-[#f0f1f8] p-5 text-center">
                                    <div className="text-3xl font-black text-[#1b265c]">{s.value}</div>
                                    <div className="text-[#555e8a] text-xs tracking-wide uppercase mt-1 leading-tight">{s.label}</div>
                                </div>
                            ))}
                        </div>

                        <p className="text-[#555e8a] leading-[1.85] mb-4">
                            ABEC members have produced peer-reviewed journal articles, IEEE conference papers, and book chapters that collectively
                            advance the global understanding of biomedical engineering education, innovation, and healthcare technology design in
                            the African context.
                        </p>
                        <p className="text-[#555e8a] leading-[1.85]">
                            Our publications inform curricula, policy decisions, and program design across the continent and internationally.
                        </p>
                    </div>
                </div>
            </section>

            {/* PUBLICATIONS */}
            <section className="bg-[#f0f1f8] py-16">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    {/* Filters */}
                    <div className="flex flex-wrap gap-6 mb-10 pb-6 border-b border-[#d0d4ec]">
                        <div>
                            <span className="text-[10px] tracking-[0.18em] uppercase text-[#555e8a] font-semibold block mb-2">Year</span>
                            <div className="flex flex-wrap gap-2">
                                {[null, ...years].map((y) => (
                                    <button
                                        key={y ?? 'all'}
                                        onClick={() => setFilter(filters, 'year', y ? String(y) : null)}
                                        className={`px-3 py-1.5 text-xs font-semibold border transition-colors ${
                                            (filters.year ?? null) === (y ? String(y) : null)
                                                ? 'bg-[#1b265c] text-white border-[#1b265c]'
                                                : 'border-[#d0d4ec] bg-white text-[#1b265c] hover:border-[#df2548]'
                                        }`}
                                    >
                                        {y ?? 'All'}
                                    </button>
                                ))}
                            </div>
                        </div>
                        <div>
                            <span className="text-[10px] tracking-[0.18em] uppercase text-[#555e8a] font-semibold block mb-2">Type</span>
                            <div className="flex flex-wrap gap-2">
                                {[null, 'journal_article', 'conference_paper', 'book_chapter'].map((t) => (
                                    <button
                                        key={t ?? 'all'}
                                        onClick={() => setFilter(filters, 'type', t)}
                                        className={`px-3 py-1.5 text-xs font-semibold border transition-colors ${
                                            (filters.type ?? null) === t
                                                ? 'bg-[#1b265c] text-white border-[#1b265c]'
                                                : 'border-[#d0d4ec] bg-white text-[#1b265c] hover:border-[#df2548]'
                                        }`}
                                    >
                                        {t ? typeLabel[t] : 'All'}
                                    </button>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Publication cards */}
                    <div className="space-y-4 mb-24">
                        {publications.length === 0 && (
                            <p className="text-[#555e8a] py-12 text-center">No publications match the selected filters.</p>
                        )}
                        {publications.map((pub, i) => {
                            const Icon = typeIcons[pub.type] ?? FileText;
                            const accent = typeAccent[pub.type] ?? 'border-l-[#d0d4ec]';
                            return (
                                <motion.div
                                    key={pub.id}
                                    initial={{ opacity: 0, y: 16 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ duration: 0.4, delay: i * 0.06 }}
                                >
                                    <Link
                                        href={`/research/${pub.id}`}
                                        className={`group block bg-white border border-[#d0d4ec] border-l-4 ${accent} hover:border-l-[#df2548] hover:shadow-md transition-all`}
                                    >
                                        <div className="flex items-start gap-6 p-7">
                                            <div className="w-10 h-10 bg-[#f0f1f8] flex items-center justify-center flex-shrink-0 group-hover:bg-[#1b265c] transition-colors mt-0.5">
                                                <Icon size={16} className="text-[#df2548] group-hover:text-white transition-colors" />
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <div className="flex flex-wrap items-center gap-3 mb-2">
                                                    <span className="px-2 py-0.5 bg-[#f0f1f8] text-[#555e8a] text-[10px] font-semibold tracking-wide uppercase">
                                                        {typeLabel[pub.type] ?? pub.type}
                                                    </span>
                                                    <span className="text-[#df2548] text-xs font-bold">{pub.year}</span>
                                                    {pub.journal && (
                                                        <span className="text-[#555e8a] text-xs italic truncate">{pub.journal}</span>
                                                    )}
                                                </div>
                                                <h3 className="text-lg font-extrabold text-[#1b265c] leading-snug mb-2 group-hover:text-[#df2548] transition-colors">
                                                    {pub.title}
                                                </h3>
                                                <p className="text-sm text-[#555e8a] mb-3 leading-relaxed">{pub.authors}</p>
                                                <p className="text-sm text-[#1b265c]/60 leading-relaxed line-clamp-3">{pub.abstract}</p>
                                                <div className="mt-4 flex items-center gap-1.5 text-[#df2548] text-xs font-semibold uppercase tracking-wider opacity-0 group-hover:opacity-100 transition-opacity">
                                                    Read More <ArrowRight size={11} />
                                                </div>
                                            </div>
                                        </div>
                                    </Link>
                                </motion.div>
                            );
                        })}
                    </div>

                    {/* Research Initiatives */}
                    <div ref={initiativesSection.ref} className="border-t border-[#d0d4ec] pt-16">
                        <div className="section-rule" />
                        <span className="label-caps block mb-4">Research Spin-offs</span>
                        <h2 className="text-3xl font-black text-[#1b265c] tracking-tight mb-10">Related Initiatives</h2>
                        <div className="grid md:grid-cols-3 gap-6">
                            {initiatives.map((init, i) => (
                                <motion.div
                                    key={init.id}
                                    initial={{ opacity: 0, y: 16 }}
                                    animate={initiativesSection.inView ? { opacity: 1, y: 0 } : {}}
                                    transition={{ duration: 0.5, delay: i * 0.1 }}
                                    className="bg-white border border-[#d0d4ec] overflow-hidden group hover:border-[#df2548] transition-colors flex flex-col"
                                >
                                    {init.cover_url && (
                                        <div className="h-40 overflow-hidden relative flex-shrink-0">
                                            <img
                                                src={init.cover_url}
                                                alt={init.title}
                                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                                            />
                                            <div className="absolute inset-0 bg-gradient-to-t from-[#1b265c]/70 to-transparent" />
                                        </div>
                                    )}
                                    <div className="p-6 flex flex-col flex-1">
                                        <h3 className="font-extrabold text-[#1b265c] leading-snug mb-3">{init.title}</h3>
                                        {init.summary && <p className="text-sm text-[#555e8a] leading-relaxed flex-1">{init.summary}</p>}
                                        {init.url && (
                                            <a
                                                href={init.url}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="mt-4 inline-flex items-center gap-1.5 text-xs font-bold text-[#df2548] hover:text-[#1b265c] transition-colors tracking-wide uppercase"
                                            >
                                                Visit Website <SquareArrowOutUpRight size={12} />
                                            </a>
                                        )}
                                    </div>
                                </motion.div>
                            ))}
                        </div>
                    </div>
                </div>
            </section>

            {/* CTA */}
            <section className="relative overflow-hidden">
                <div className="absolute inset-0">
                    <img src="/images/lab-blood-samples-redlight.jpg" alt="" className="w-full h-full object-cover" />
                    <div className="absolute inset-0" style={{ background: 'linear-gradient(to right, rgba(10,38,71,0.97) 0%, rgba(10,38,71,0.92) 40%, rgba(10,38,71,0.35) 65%, transparent 100%)' }} />
                </div>
                <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-24">
                    <div className="max-w-lg">
                        <span className="text-[#d0d4ec]/60 text-xs tracking-[0.2em] uppercase font-semibold block mb-3">Research &amp; Innovation</span>
                        <h2 className="text-4xl font-black text-white tracking-tight mb-4">Contribute to the Field</h2>
                        <p className="text-white/60 leading-relaxed mb-8 text-sm">
                            ABEC members publish, collaborate, and present across the continent. Join to access the research network and submit your work.
                        </p>
                        <Link
                            href="/join"
                            className="inline-flex items-center gap-2 h-12 px-8 bg-[#d0d4ec] text-[#1b265c] text-xs font-bold tracking-[0.15em] uppercase hover:bg-white transition-colors"
                        >
                            Join ABEC <ArrowRight size={14} />
                        </Link>
                    </div>
                </div>
            </section>
        </div>
    );
}

Research.layout = (page: React.ReactNode) => <PublicLayout>{page}</PublicLayout>;
