import { Head, Link, usePage } from '@inertiajs/react';
import { motion, useScroll, useTransform } from 'framer-motion';
import { useRef } from 'react';
import { 
    FileText, 
    MessageSquare, 
    BarChart3, 
    Users, 
    Shield, 
    Leaf,
    BookOpen,
    ArrowRight,
    ExternalLink,
    Sparkles,
    Globe
} from 'lucide-react';
import PublicLayout from '@/layouts/public-layout';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { type SharedData } from '@/types';

// Animation variants
const fadeInUp = {
    hidden: { opacity: 0, y: 40 },
    visible: { 
        opacity: 1, 
        y: 0,
        transition: { duration: 0.6, ease: [0.22, 1, 0.36, 1] }
    }
};

const fadeInScale = {
    hidden: { opacity: 0, scale: 0.9 },
    visible: { 
        opacity: 1, 
        scale: 1,
        transition: { duration: 0.5, ease: [0.22, 1, 0.36, 1] }
    }
};

const staggerContainer = {
    hidden: { opacity: 0 },
    visible: {
        opacity: 1,
        transition: {
            staggerChildren: 0.1,
            delayChildren: 0.2
        }
    }
};

const scaleOnHover = {
    rest: { scale: 1 },
    hover: { 
        scale: 1.02,
        transition: { duration: 0.3, ease: [0.22, 1, 0.36, 1] }
    }
};

interface FeatureCardProps {
    icon: React.ElementType;
    title: string;
    description: string;
    index: number;
}

function FeatureCard({ icon: Icon, title, description, index }: FeatureCardProps) {
    return (
        <motion.div
            variants={fadeInUp}
            initial="rest"
            whileHover="hover"
            className="group"
        >
            <motion.div variants={scaleOnHover}>
                <Card className="h-full bg-card/50 backdrop-blur-sm border-border/50 hover:border-forest/30 hover:shadow-xl hover:shadow-forest/5 transition-all duration-500">
                    <CardHeader>
                        <motion.div 
                            className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-forest/20 to-forest/5 text-forest group-hover:from-forest group-hover:to-forest-light group-hover:text-white transition-all duration-500"
                            whileHover={{ rotate: [0, -5, 5, 0] }}
                            transition={{ duration: 0.5 }}
                        >
                            <Icon className="h-7 w-7" />
                        </motion.div>
                        <CardTitle className="mt-4 text-xl">{title}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <CardDescription className="text-base leading-relaxed">{description}</CardDescription>
                    </CardContent>
                </Card>
            </motion.div>
        </motion.div>
    );
}

interface ProjectCardProps {
    title: string;
    description: string;
    badge: string;
    badgeColor: 'active' | 'development' | 'soon';
    href?: string;
}

function ProjectCard({ title, description, badge, badgeColor, href }: ProjectCardProps) {
    const badgeColors = {
        active: 'bg-forest/20 text-forest border-forest/30',
        development: 'bg-ochre/20 text-ochre border-ochre/30',
        soon: 'bg-terracotta/20 text-terracotta border-terracotta/30'
    };

    const content = (
        <motion.div
            variants={fadeInUp}
            whileHover={{ y: -5 }}
            transition={{ duration: 0.3 }}
        >
            <Card className="h-full bg-card/50 backdrop-blur-sm border-border/50 hover:border-ochre/30 hover:shadow-xl hover:shadow-ochre/5 transition-all duration-500">
                <CardHeader>
                    <div className="flex items-start justify-between gap-4">
                        <CardTitle className="text-lg">{title}</CardTitle>
                        <Badge variant="secondary" className={badgeColors[badgeColor]}>
                            {badge}
                        </Badge>
                    </div>
                </CardHeader>
                <CardContent>
                    <CardDescription className="leading-relaxed">{description}</CardDescription>
                    {href && (
                        <motion.div 
                            className="mt-4 flex items-center gap-1 text-sm text-forest font-medium"
                            whileHover={{ x: 5 }}
                        >
                            Ver más <ExternalLink className="h-4 w-4" />
                        </motion.div>
                    )}
                </CardContent>
            </Card>
        </motion.div>
    );

    if (href) {
        return (
            <a href={href} target="_blank" rel="noopener noreferrer">
                {content}
            </a>
        );
    }

    return content;
}

function HeroSection() {
    const { auth } = usePage<SharedData>().props;
    const ref = useRef(null);
    const { scrollYProgress } = useScroll({
        target: ref,
        offset: ["start start", "end start"]
    });

    const y = useTransform(scrollYProgress, [0, 1], ["0%", "30%"]);
    const opacity = useTransform(scrollYProgress, [0, 0.5], [1, 0]);

    return (
        <section ref={ref} className="relative min-h-[90vh] flex items-center overflow-hidden">
            {/* Animated background */}
            <div className="absolute inset-0 -z-10">
                {/* Gradient orbs */}
                <motion.div
                    className="absolute top-20 left-1/4 h-96 w-96 rounded-full bg-forest/20 blur-[100px]"
                    animate={{ 
                        scale: [1, 1.2, 1],
                        opacity: [0.3, 0.5, 0.3]
                    }}
                    transition={{ duration: 8, repeat: Infinity, ease: "easeInOut" }}
                />
                <motion.div
                    className="absolute bottom-20 right-1/4 h-80 w-80 rounded-full bg-ochre/20 blur-[100px]"
                    animate={{ 
                        scale: [1.2, 1, 1.2],
                        opacity: [0.4, 0.2, 0.4]
                    }}
                    transition={{ duration: 10, repeat: Infinity, ease: "easeInOut" }}
                />
                <motion.div
                    className="absolute top-1/2 right-1/3 h-64 w-64 rounded-full bg-terracotta/10 blur-[80px]"
                    animate={{ 
                        x: [0, 50, 0],
                        y: [0, -30, 0]
                    }}
                    transition={{ duration: 12, repeat: Infinity, ease: "easeInOut" }}
                />
            </div>

            {/* Grid pattern */}
            <div className="absolute inset-0 -z-10 bg-[linear-gradient(rgba(26,77,46,0.03)_1px,transparent_1px),linear-gradient(90deg,rgba(26,77,46,0.03)_1px,transparent_1px)] bg-[size:60px_60px]" />

            <motion.div 
                className="container mx-auto px-4 py-20"
                style={{ y, opacity }}
            >
                <motion.div 
                    className="flex flex-col items-center text-center"
                    variants={staggerContainer}
                    initial="hidden"
                    animate="visible"
                >
                    {/* Logo with glow effect */}
                    <motion.div 
                        className="relative mb-8"
                        variants={fadeInScale}
                    >
                        <div className="absolute inset-0 bg-forest/30 rounded-3xl blur-2xl animate-pulse" />
                        <div className="relative flex h-28 w-28 items-center justify-center rounded-3xl bg-gradient-to-br from-forest to-forest-light text-white shadow-2xl shadow-forest/40">
                            <svg
                                viewBox="0 0 24 24"
                                fill="none"
                                className="h-16 w-16"
                                stroke="currentColor"
                                strokeWidth="1.2"
                            >
                                <path d="M12 2L21.5 7.5V16.5L12 22L2.5 16.5V7.5L12 2Z" />
                                <circle cx="12" cy="12" r="4" />
                                <path d="M12 8V16M8 12H16" strokeWidth="0.8" />
                            </svg>
                        </div>
                    </motion.div>

                    {/* Badge */}
                    <motion.div variants={fadeInUp}>
                        <Badge variant="secondary" className="mb-6 px-4 py-1.5 text-sm bg-forest/10 text-forest border-forest/20">
                            <Sparkles className="h-3.5 w-3.5 mr-1.5" />
                            Hub de Conocimiento Intercultural
                        </Badge>
                    </motion.div>

                    {/* Title with gradient */}
                    <motion.h1 
                        className="text-5xl font-bold tracking-tight sm:text-6xl lg:text-7xl"
                        variants={fadeInUp}
                    >
                        <span className="bg-gradient-to-r from-forest via-forest-light to-forest bg-clip-text text-transparent">
                            Ser Ajayu
                        </span>
                    </motion.h1>

                    {/* Subtitle with animated words */}
                    <motion.p 
                        className="mt-8 max-w-2xl text-lg text-muted-foreground lg:text-xl leading-relaxed"
                        variants={fadeInUp}
                    >
                        Integrando saberes ancestrales andinos y amazónicos con
                        conocimiento científico moderno para la salud mental, de manera
                        <motion.span 
                            className="text-forest font-semibold mx-1"
                            whileHover={{ scale: 1.05 }}
                        >
                            colaborativa
                        </motion.span>,
                        <motion.span 
                            className="text-terracotta font-semibold mx-1"
                            whileHover={{ scale: 1.05 }}
                        >
                            respetuosa
                        </motion.span> y
                        <motion.span 
                            className="text-ochre font-semibold mx-1"
                            whileHover={{ scale: 1.05 }}
                        >
                            regulada
                        </motion.span>.
                    </motion.p>

                    {/* CTA Buttons with hover effects */}
                    <motion.div 
                        className="mt-12 flex flex-col sm:flex-row gap-4"
                        variants={fadeInUp}
                    >
                        <Link href="/documentos">
                            <motion.div
                                whileHover={{ scale: 1.02 }}
                                whileTap={{ scale: 0.98 }}
                            >
                                <Button size="lg" className="bg-forest hover:bg-forest-light gap-2 shadow-lg shadow-forest/25 px-8 h-12 text-base">
                                    <BookOpen className="h-5 w-5" />
                                    Explorar Documentos
                                </Button>
                            </motion.div>
                        </Link>
                        {!auth.user && (
                            <Link href="/register">
                                <motion.div
                                    whileHover={{ scale: 1.02 }}
                                    whileTap={{ scale: 0.98 }}
                                >
                                    <Button size="lg" variant="outline" className="gap-2 border-2 px-8 h-12 text-base hover:bg-forest/5 hover:border-forest">
                                        <Users className="h-5 w-5" />
                                        Unirse a la Comunidad
                                    </Button>
                                </motion.div>
                            </Link>
                        )}
                    </motion.div>

                    {/* Stats */}
                    <motion.div 
                        className="mt-16 flex flex-wrap justify-center gap-8 lg:gap-16"
                        variants={fadeInUp}
                    >
                        {[
                            { number: '50+', label: 'Documentos' },
                            { number: '100+', label: 'Miembros' },
                            { number: '5', label: 'Proyectos' },
                        ].map((stat, index) => (
                            <motion.div 
                                key={stat.label}
                                className="text-center"
                                whileHover={{ y: -3 }}
                            >
                                <div className="text-3xl lg:text-4xl font-bold text-forest">{stat.number}</div>
                                <div className="text-sm text-muted-foreground mt-1">{stat.label}</div>
                            </motion.div>
                        ))}
                    </motion.div>
                </motion.div>
            </motion.div>

            {/* Scroll indicator */}
            <motion.div 
                className="absolute bottom-8 left-1/2 -translate-x-1/2"
                animate={{ y: [0, 10, 0] }}
                transition={{ duration: 2, repeat: Infinity }}
            >
                <div className="w-6 h-10 rounded-full border-2 border-muted-foreground/30 flex items-start justify-center p-2">
                    <motion.div 
                        className="w-1.5 h-1.5 rounded-full bg-forest"
                        animate={{ y: [0, 12, 0] }}
                        transition={{ duration: 2, repeat: Infinity }}
                    />
                </div>
            </motion.div>
        </section>
    );
}

function FeaturesSection() {
    const features = [
        {
            icon: FileText,
            title: 'Repositorio de Documentos',
            description: 'Biblioteca virtual con documentos, audios y videos sobre etnofarmacología, protocolos terapéuticos y prácticas ancestrales.',
        },
        {
            icon: BookOpen,
            title: 'Documentos Colaborativos',
            description: 'Construcción colectiva de protocolos, propuestas de regulación y documentos estratégicos con edición en tiempo real.',
        },
        {
            icon: MessageSquare,
            title: 'Foros de Discusión',
            description: 'Espacios de diálogo intercultural para discutir incidencia política, conocimiento colectivo y nuevos proyectos.',
        },
        {
            icon: BarChart3,
            title: 'Encuestas Digitales',
            description: 'Herramientas para generar información y orientar procesos de investigación e incidencia política.',
        },
        {
            icon: Shield,
            title: 'Prácticas Responsables',
            description: 'Énfasis en evaluación crítica, respeto cultural y prevención de extractivismo cultural.',
        },
        {
            icon: Leaf,
            title: 'Conocimiento Ancestral',
            description: 'Reconocimiento de la diversidad biocultural andina-amazónica y sistemas de certificación.',
        },
    ];

    return (
        <section className="py-24 lg:py-32 relative overflow-hidden">
            {/* Background decoration */}
            <div className="absolute inset-0 -z-10">
                <div className="absolute top-1/2 left-0 w-1/2 h-px bg-gradient-to-r from-transparent via-border to-transparent" />
            </div>

            <div className="container mx-auto px-4">
                <motion.div 
                    className="text-center mb-16"
                    initial={{ opacity: 0, y: 30 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    viewport={{ once: true }}
                    transition={{ duration: 0.6 }}
                >
                    <Badge variant="secondary" className="mb-4 bg-sage/30 text-earth border-sage">
                        <Globe className="h-3.5 w-3.5 mr-1.5" />
                        Funcionalidades
                    </Badge>
                    <h2 className="text-3xl font-bold text-foreground lg:text-5xl">
                        Todo lo que necesitas
                    </h2>
                    <p className="mt-4 text-lg text-muted-foreground max-w-2xl mx-auto">
                        Herramientas diseñadas para facilitar el intercambio de conocimientos
                        con respeto cultural y rigor científico.
                    </p>
                </motion.div>

                <motion.div 
                    className="grid gap-6 md:grid-cols-2 lg:grid-cols-3"
                    variants={staggerContainer}
                    initial="hidden"
                    whileInView="visible"
                    viewport={{ once: true, margin: "-100px" }}
                >
                    {features.map((feature, index) => (
                        <FeatureCard key={feature.title} {...feature} index={index} />
                    ))}
                </motion.div>
            </div>
        </section>
    );
}

function ProjectsSection() {
    const projects = [
        {
            title: 'Proyecto Sonoro',
            description: 'Plantas sagradas y su dimensión sonora en las tradiciones andinas y amazónicas. Documentación de cantos y ceremonias.',
            badge: 'Activo',
            badgeColor: 'active' as const,
            href: 'https://giveth.io/project/sound-of-sacred-plants-in-the-face-of-modern-crises',
        },
        {
            title: 'Hub de Conocimiento',
            description: 'Proyecto marco para la integración de saberes ancestrales con evidencia científica moderna.',
            badge: 'En desarrollo',
            badgeColor: 'development' as const,
        },
        {
            title: 'Proyecto Video',
            description: 'Documentación audiovisual de prácticas tradicionales y testimonios de comunidades.',
            badge: 'Próximamente',
            badgeColor: 'soon' as const,
        },
    ];

    return (
        <section className="py-24 lg:py-32 bg-muted/30 relative">
            {/* Decorative elements */}
            <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-border to-transparent" />
            <div className="absolute bottom-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-border to-transparent" />

            <div className="container mx-auto px-4">
                <motion.div 
                    className="text-center mb-16"
                    initial={{ opacity: 0, y: 30 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    viewport={{ once: true }}
                    transition={{ duration: 0.6 }}
                >
                    <Badge variant="secondary" className="mb-4 bg-ochre/20 text-ochre border-ochre/30">
                        ✨ Iniciativas
                    </Badge>
                    <h2 className="text-3xl font-bold text-foreground lg:text-5xl">
                        Nuestros Proyectos
                    </h2>
                    <p className="mt-4 text-lg text-muted-foreground max-w-2xl mx-auto">
                        Iniciativas para promover el diálogo intercultural y la incidencia política.
                    </p>
                </motion.div>

                <motion.div 
                    className="grid gap-6 md:grid-cols-3"
                    variants={staggerContainer}
                    initial="hidden"
                    whileInView="visible"
                    viewport={{ once: true, margin: "-100px" }}
                >
                    {projects.map((project) => (
                        <ProjectCard key={project.title} {...project} />
                    ))}
                </motion.div>

                <motion.div 
                    className="mt-12 text-center"
                    initial={{ opacity: 0 }}
                    whileInView={{ opacity: 1 }}
                    viewport={{ once: true }}
                    transition={{ delay: 0.4 }}
                >
                    <Link href="/proyectos">
                        <motion.div
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98 }}
                            className="inline-block"
                        >
                            <Button variant="outline" className="gap-2 border-2 hover:border-forest hover:text-forest">
                                Ver todos los proyectos
                                <ArrowRight className="h-4 w-4" />
                            </Button>
                        </motion.div>
                    </Link>
                </motion.div>
            </div>
        </section>
    );
}

function CTASection() {
    const { auth } = usePage<SharedData>().props;

    return (
        <section className="py-24 lg:py-32">
            <div className="container mx-auto px-4">
                <motion.div 
                    className="relative overflow-hidden rounded-3xl"
                    initial={{ opacity: 0, y: 40 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    viewport={{ once: true }}
                    transition={{ duration: 0.8 }}
                >
                    {/* Gradient background */}
                    <div className="absolute inset-0 bg-gradient-to-br from-forest via-forest-light to-forest" />
                    
                    {/* Animated pattern */}
                    <div className="absolute inset-0">
                        <motion.div
                            className="absolute top-0 right-0 w-96 h-96 bg-white/10 rounded-full blur-3xl"
                            animate={{ 
                                x: [0, 30, 0],
                                y: [0, -20, 0]
                            }}
                            transition={{ duration: 8, repeat: Infinity }}
                        />
                        <motion.div
                            className="absolute bottom-0 left-0 w-80 h-80 bg-ochre/20 rounded-full blur-3xl"
                            animate={{ 
                                x: [0, -20, 0],
                                y: [0, 30, 0]
                            }}
                            transition={{ duration: 10, repeat: Infinity }}
                        />
                    </div>

                    {/* Grid pattern overlay */}
                    <div className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.05)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.05)_1px,transparent_1px)] bg-[size:40px_40px]" />

                    <div className="relative p-8 lg:p-20 text-center text-white">
                        <motion.div
                            initial={{ opacity: 0, y: 20 }}
                            whileInView={{ opacity: 1, y: 0 }}
                            viewport={{ once: true }}
                            transition={{ delay: 0.2 }}
                        >
                            <h2 className="text-3xl font-bold lg:text-5xl">
                                Únete a nuestra comunidad
                            </h2>
                            <p className="mt-6 text-lg text-white/80 max-w-2xl mx-auto leading-relaxed">
                                Participa en la construcción de conocimiento colectivo sobre terapias
                                enteógenas responsables para la salud mental.
                            </p>
                        </motion.div>
                        
                        {!auth.user && (
                            <motion.div 
                                className="mt-10 flex flex-col sm:flex-row gap-4 justify-center"
                                initial={{ opacity: 0, y: 20 }}
                                whileInView={{ opacity: 1, y: 0 }}
                                viewport={{ once: true }}
                                transition={{ delay: 0.4 }}
                            >
                                <Link href="/register">
                                    <motion.div
                                        whileHover={{ scale: 1.02 }}
                                        whileTap={{ scale: 0.98 }}
                                    >
                                        <Button size="lg" className="bg-white text-forest hover:bg-white/90 gap-2 shadow-xl px-8 h-12 text-base font-semibold">
                                            Crear una cuenta
                                            <ArrowRight className="h-5 w-5" />
                                        </Button>
                                    </motion.div>
                                </Link>
                                <a 
                                    href="https://docs.google.com/document/d/1gkTca5SVlL0JthoeiceEUZBCvnBR3d3tPorGBhRiWrk/edit?usp=sharing"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    <motion.div
                                        whileHover={{ scale: 1.02 }}
                                        whileTap={{ scale: 0.98 }}
                                    >
                                        <Button size="lg" variant="outline" className="border-2 border-white/50 text-white hover:bg-white/10 hover:border-white gap-2 px-8 h-12 text-base">
                                            Ver políticas
                                            <ExternalLink className="h-5 w-5" />
                                        </Button>
                                    </motion.div>
                                </a>
                            </motion.div>
                        )}
                    </div>
                </motion.div>
            </div>
        </section>
    );
}

export default function Welcome() {
    return (
        <PublicLayout showBottomNav={true}>
            <Head title="Ser Ajayu - Hub de Conocimiento Intercultural" />
            
            <HeroSection />
            <FeaturesSection />
            <ProjectsSection />
            <CTASection />
        </PublicLayout>
    );
}
