import Seo from '@/components/Seo';
import PlatformLayout from '@/Layouts/PlatformLayout';
import { resolveIcon } from '@/lib/icon-map';
import type { ArticleSummary } from '@/types/platform';
import { Link } from '@inertiajs/react';
import { motion, useInView } from 'framer-motion';
import { ArrowRight, BookOpen, Clock, Filter, Play } from 'lucide-react';
import { useMemo, useRef, useState } from 'react';

const ease = [0.16, 1, 0.3, 1] as const;

function FadeUp({
    children,
    delay = 0,
    className,
}: {
    children: React.ReactNode;
    delay?: number;
    className?: string;
}) {
    const ref = useRef<HTMLDivElement>(null);
    const inView = useInView(ref, { once: true, margin: '-60px' });
    return (
        <motion.div
            ref={ref}
            initial={{ opacity: 0, y: 28 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.65, delay, ease }}
            className={className}
        >
            {children}
        </motion.div>
    );
}

const levelColors: Record<string, string> = {
    Beginner: 'text-emerald-600 bg-emerald-500/10',
    Intermediate: 'text-amber-600 bg-amber-500/10',
    Advanced: 'text-rose-600 bg-rose-500/10',
};

interface Props {
    articles: ArticleSummary[];
}

export default function Tutorials({ articles }: Props) {
    const [activeCategory, setActiveCategory] = useState('All');

    const categories = useMemo(
        () => [
            'All',
            ...Array.from(
                new Set(articles.map((a) => a.category).filter(Boolean)),
            ),
        ],
        [articles],
    ) as string[];

    const filtered =
        activeCategory === 'All'
            ? articles
            : articles.filter((t) => t.category === activeCategory);

    return (
        <PlatformLayout>
            <Seo
                title="Tutorials"
                description="Step-by-step tutorials for getting the most out of Upepo Finance's loan, savings, and accounting modules."
            />

            {/* Hero */}
            <section className="relative overflow-hidden pt-32 pb-20">
                <div className="pointer-events-none absolute inset-0 overflow-hidden">
                    <div
                        className="pf-blob pf-blob-1 absolute -top-24 left-1/3 h-[420px] w-[420px] opacity-20"
                        style={{
                            background:
                                'radial-gradient(circle, hsl(var(--primary) / 0.45), transparent 70%)',
                        }}
                    />
                </div>
                <div className="pf-container relative z-10 mx-auto max-w-3xl text-center">
                    <FadeUp delay={0.1}>
                        <h1 className="pf-display text-foreground mb-6 text-4xl font-bold md:text-5xl">
                            Learn at your{' '}
                            <span className="pf-gradient-text">own pace</span>
                        </h1>
                    </FadeUp>
                    <FadeUp delay={0.2}>
                        <p className="text-muted-foreground text-lg leading-relaxed">
                            Step-by-step video walkthroughs and written guides
                            for every feature — from first login to advanced
                            configuration.
                        </p>
                    </FadeUp>
                </div>
            </section>

            {/* Filter bar */}
            <div className="border-border bg-card/60 sticky top-16 z-30 border-b py-3 backdrop-blur-sm">
                <div className="pf-container">
                    <div className="flex items-center gap-3 overflow-x-auto">
                        <Filter className="text-muted-foreground h-4 w-4 shrink-0" />
                        {categories.map((cat) => (
                            <button
                                key={cat}
                                onClick={() => setActiveCategory(cat)}
                                className={`shrink-0 rounded-xl px-4 py-1.5 text-sm font-medium transition-all ${
                                    activeCategory === cat
                                        ? 'bg-primary text-primary-foreground'
                                        : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
                                }`}
                            >
                                {cat}
                            </button>
                        ))}
                    </div>
                </div>
            </div>

            {/* Tutorials grid */}
            <section className="pf-section">
                <div className="pf-container">
                    <div className="mb-6 flex items-center justify-between">
                        <p className="text-muted-foreground text-sm">
                            {filtered.length} tutorial
                            {filtered.length !== 1 ? 's' : ''}
                        </p>
                    </div>
                    <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                        {filtered.map((tutorial, i) => {
                            const Icon = resolveIcon(tutorial.icon);
                            return (
                                <FadeUp key={tutorial.slug} delay={i * 0.06}>
                                    <motion.div
                                        whileHover={{ y: -5, scale: 1.01 }}
                                        transition={{ duration: 0.25 }}
                                        className="pf-card group flex h-full flex-col p-6"
                                    >
                                        <div className="mb-4 flex items-start justify-between gap-3">
                                            <div className="pf-icon-box h-10 w-10 shrink-0">
                                                <Icon className="h-5 w-5" />
                                            </div>
                                            <div className="flex items-center gap-2">
                                                {tutorial.level && (
                                                    <span
                                                        className={`rounded-lg px-2 py-0.5 text-[10px] font-semibold ${levelColors[tutorial.level]}`}
                                                    >
                                                        {tutorial.level}
                                                    </span>
                                                )}
                                                {tutorial.format && (
                                                    <span className="border-border bg-secondary/60 text-muted-foreground rounded-lg border px-2 py-0.5 text-[10px] font-medium">
                                                        {tutorial.format}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                        <h3 className="text-foreground group-hover:text-primary mb-3 leading-snug font-semibold transition-colors">
                                            {tutorial.title}
                                        </h3>
                                        <p className="text-muted-foreground mb-5 flex-1 text-sm leading-relaxed">
                                            {tutorial.excerpt}
                                        </p>
                                        <div className="flex items-center justify-between">
                                            <div className="text-muted-foreground flex items-center gap-1.5 text-xs">
                                                <Clock className="h-3 w-3" />
                                                {tutorial.duration}
                                            </div>
                                            <Link
                                                href={`/tutorials/${tutorial.slug}`}
                                                className="text-primary flex items-center gap-1.5 text-xs font-semibold transition-opacity hover:opacity-70"
                                            >
                                                {tutorial.format === 'Video' ? (
                                                    <Play className="h-3.5 w-3.5" />
                                                ) : (
                                                    <BookOpen className="h-3.5 w-3.5" />
                                                )}
                                                {tutorial.format === 'Video'
                                                    ? 'Watch'
                                                    : 'Read guide'}
                                            </Link>
                                        </div>
                                    </motion.div>
                                </FadeUp>
                            );
                        })}
                    </div>
                </div>
            </section>

            {/* CTA */}
            <section className="pf-section pf-section-dark">
                <div className="pf-container text-center">
                    <FadeUp>
                        <h2 className="pf-display mb-4 text-3xl font-bold">
                            Can't find what you need?
                        </h2>
                        <p className="mx-auto mb-10 max-w-sm text-sm opacity-80">
                            Browse the full help centre or contact our support
                            team directly.
                        </p>
                        <div className="flex flex-wrap justify-center gap-4">
                            <Link
                                href="/help"
                                className="pf-btn inline-flex items-center gap-2 px-8 py-3.5 text-base"
                            >
                                Browse help centre{' '}
                                <ArrowRight className="h-4 w-4" />
                            </Link>
                            <Link
                                href="/support"
                                className="pf-btn-ghost inline-flex items-center gap-2 px-8 py-3.5 text-base"
                            >
                                Contact support
                            </Link>
                        </div>
                    </FadeUp>
                </div>
            </section>
        </PlatformLayout>
    );
}
