import { Head, Link } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { useState } from 'react';
import { 
    FileText, 
    Search, 
    Grid3X3, 
    List,
    Download,
    ExternalLink,
    Filter,
    Calendar,
    User,
    Folder,
    ChevronRight,
    FileType,
    BookOpen,
    HardDrive
} from 'lucide-react';
import PublicLayout from '@/layouts/public-layout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"

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

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

// Document types
type DocumentCategory = 'etnobotanica' | 'psicologia' | 'antropologia' | 'protocolos' | 'practicas';

interface Document {
    id: string;
    title: string;
    author: string;
    description: string;
    category: DocumentCategory;
    type: 'pdf' | 'docx' | 'video' | 'audio';
    driveUrl: string;
    year?: number;
    size?: string;
}

// Mock data from the technical document
const documents: Document[] = [
    {
        id: '1',
        title: 'Las plantas de los dioses',
        author: 'Evans, Richard; Hofmann, Albert; Rätsch, Christian',
        description: 'Las fuerzas mágicas de las plantas alucinógenas. Una obra fundamental sobre etnobotánica.',
        category: 'etnobotanica',
        type: 'pdf',
        driveUrl: 'https://drive.google.com/file/d/1ATRX0NbQBX6_6Cs7Fnf8jJyO-pSGfvO9/view?usp=sharing',
        year: 1992,
        size: '45 MB'
    },
    {
        id: '2',
        title: 'El hombre que volvió a nacer',
        author: 'Flores Apaza, Policarpio (et al)',
        description: 'Vida, saberes y reflexiones de un amawta de Tiwanaku. Conocimiento ancestral boliviano.',
        category: 'practicas',
        type: 'pdf',
        driveUrl: 'https://drive.google.com/file/d/1-Eb_zdWmNuws59P_rcgC5wxonYo1fDgK/view?usp=sharing',
        year: 2005,
        size: '12 MB'
    },
    {
        id: '3',
        title: 'Plantas medicinales de La Paz y El Alto',
        author: 'Maida, Justo-Chipana; Moraes, Mónica',
        description: 'Plantas medicinales comercializadas por las chifleras de La Paz y El Alto (Bolivia).',
        category: 'etnobotanica',
        type: 'docx',
        driveUrl: 'https://docs.google.com/document/d/1Qi9Az3hlWIDAfQMBlYCuwHjp5NDu7ikb/edit?usp=sharing',
        size: '2.3 MB'
    },
    {
        id: '4',
        title: 'Resignificación de la identidad mediante consumo de Yajé',
        author: 'Marulanda Mejía, Tulio (et al)',
        description: 'Estudio sobre la resignificación de la identidad cultural a través del uso ceremonial del Yajé.',
        category: 'antropologia',
        type: 'pdf',
        driveUrl: 'https://drive.google.com/file/d/1xofbuNjwKHzDEoZs_4-FUmb3wu5kU5Pt/view?usp=sharing',
        size: '8.5 MB'
    },
    {
        id: '5',
        title: 'The Healing Journey',
        author: 'Naranjo, Claudio',
        description: 'Pioneering Approaches to Psychedelic Therapy. Un clásico de la psicoterapia psicodélica.',
        category: 'psicologia',
        type: 'pdf',
        driveUrl: 'https://drive.google.com/file/d/1bq92cuL0TIgrm4yWfeotHTrh9gyCYSBZ/view?usp=sharing',
        year: 1973,
        size: '15 MB'
    },
    {
        id: '6',
        title: 'La psilocibina: perspectiva histórica y farmacológica',
        author: 'Serrano Hurtado, David',
        description: 'Perspectiva histórica y farmacológica e investigaciones actuales autorizadas sobre psilocibina.',
        category: 'psicologia',
        type: 'pdf',
        driveUrl: 'https://drive.google.com/file/d/1vU9EDdNtLxHphKugCfl7ZBA6RBn__2-x/view?usp=sharing',
        size: '4.2 MB'
    },
    {
        id: '7',
        title: 'Evidencias del impacto del uso ceremonial de Ayahuasca',
        author: 'Timmer, Hilvert',
        description: 'Evidence of the Impact of the ceremonial use of ayahuasca in a Healing Center in Bolivia.',
        category: 'protocolos',
        type: 'pdf',
        driveUrl: 'https://drive.google.com/file/d/1WnsjYpU5kpY3nWnCAc_MpPg8Te_ifS70/view?usp=sharing',
        year: 2021,
        size: '3.8 MB'
    },
];

const categories: { value: DocumentCategory | 'all'; label: string }[] = [
    { value: 'all', label: 'Todas las categorías' },
    { value: 'etnobotanica', label: 'Etnobotánica' },
    { value: 'psicologia', label: 'Psicología' },
    { value: 'antropologia', label: 'Antropología' },
    { value: 'protocolos', label: 'Protocolos de salud' },
    { value: 'practicas', label: 'Prácticas ancestrales' },
];

const categoryColors: Record<DocumentCategory, string> = {
    etnobotanica: 'bg-forest/10 text-forest border-forest/20',
    psicologia: 'bg-ochre/10 text-ochre border-ochre/20',
    antropologia: 'bg-terracotta/10 text-terracotta border-terracotta/20',
    protocolos: 'bg-sage/30 text-earth border-sage',
    practicas: 'bg-earth/10 text-earth border-earth/20',
};

const categoryLabels: Record<DocumentCategory, string> = {
    etnobotanica: 'Etnobotánica',
    psicologia: 'Psicología',
    antropologia: 'Antropología',
    protocolos: 'Protocolos',
    practicas: 'Prácticas ancestrales',
};

function getFileIcon(type: Document['type']) {
    switch (type) {
        case 'pdf':
            return <FileText className="h-8 w-8 text-red-500" />;
        case 'docx':
            return <FileType className="h-8 w-8 text-blue-500" />;
        case 'video':
            return <FileText className="h-8 w-8 text-purple-500" />;
        case 'audio':
            return <FileText className="h-8 w-8 text-green-500" />;
        default:
            return <FileText className="h-8 w-8 text-gray-500" />;
    }
}

interface DocumentCardProps {
    document: Document;
    viewMode: 'grid' | 'list';
    onSelect: () => void;
}

function DocumentCard({ document, viewMode, onSelect }: DocumentCardProps) {
    if (viewMode === 'list') {
        return (
            <motion.div variants={fadeInUp}>
                <button 
                    onClick={onSelect}
                    className="block w-full text-left"
                >
                    <Card className="group hover:border-forest/30 hover:shadow-lg transition-all duration-300">
                        <CardContent className="p-4">
                            <div className="flex items-center gap-4">
                                {/* File icon */}
                                <div className="shrink-0 p-3 rounded-xl bg-muted/50 group-hover:bg-forest/10 transition-colors">
                                    {getFileIcon(document.type)}
                                </div>
                                
                                {/* Content */}
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-start justify-between gap-4">
                                        <div className="min-w-0">
                                            <h3 className="font-semibold text-foreground truncate group-hover:text-forest transition-colors">
                                                {document.title}
                                            </h3>
                                            <p className="text-sm text-muted-foreground flex items-center gap-2 mt-1">
                                                <User className="h-3.5 w-3.5" />
                                                <span className="truncate">{document.author}</span>
                                            </p>
                                        </div>
                                        <div className="flex items-center gap-2 shrink-0">
                                            <Badge className={cn('text-xs', categoryColors[document.category])}>
                                                {categoryLabels[document.category]}
                                            </Badge>
                                            <ExternalLink className="h-4 w-4 text-muted-foreground group-hover:text-forest transition-colors" />
                                        </div>
                                    </div>
                                    <p className="text-sm text-muted-foreground mt-2 line-clamp-1">
                                        {document.description}
                                    </p>
                                    <div className="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
                                        {document.year && (
                                            <span className="flex items-center gap-1">
                                                <Calendar className="h-3 w-3" />
                                                {document.year}
                                            </span>
                                        )}
                                        {document.size && (
                                            <span className="flex items-center gap-1">
                                                <Download className="h-3 w-3" />
                                                {document.size}
                                            </span>
                                        )}
                                        <span className="uppercase">{document.type}</span>
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </button>
            </motion.div>
        );
    }

    // Grid view
    return (
        <motion.div variants={fadeInUp}>
            <button 
                onClick={onSelect}
                className="block h-full w-full text-left"
            >
                <Card className="h-full group hover:border-forest/30 hover:shadow-xl transition-all duration-300 overflow-hidden">
                    {/* File preview area */}
                    <div className="relative h-32 bg-linear-to-br from-muted to-muted/50 flex items-center justify-center">
                        <motion.div
                            className="p-4 rounded-2xl bg-background/80 shadow-lg"
                            whileHover={{ scale: 1.1, rotate: 5 }}
                            transition={{ type: 'spring', stiffness: 400, damping: 17 }}
                        >
                            {getFileIcon(document.type)}
                        </motion.div>
                        <Badge 
                            className={cn('absolute top-3 right-3 text-xs', categoryColors[document.category])}
                        >
                            {categoryLabels[document.category]}
                        </Badge>
                    </div>
                    
                    <CardContent className="p-4">
                        <h3 className="font-semibold text-foreground line-clamp-2 group-hover:text-forest transition-colors min-h-[48px]">
                            {document.title}
                        </h3>
                        <p className="text-sm text-muted-foreground mt-2 flex items-center gap-1.5">
                            <User className="h-3.5 w-3.5 shrink-0" />
                            <span className="truncate">{document.author}</span>
                        </p>
                        <p className="text-sm text-muted-foreground mt-2 line-clamp-2">
                            {document.description}
                        </p>
                        <div className="flex items-center justify-between mt-4 pt-3 border-t border-border">
                            <div className="flex items-center gap-3 text-xs text-muted-foreground">
                                {document.year && (
                                    <span>{document.year}</span>
                                )}
                                <span className="uppercase font-medium">{document.type}</span>
                            </div>
                            <ExternalLink className="h-4 w-4 text-muted-foreground group-hover:text-forest transition-colors" />
                        </div>
                    </CardContent>
                </Card>
            </button>
        </motion.div>
    );
}

export default function DocumentosIndex() {
    const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState<DocumentCategory | 'all'>('all');
    const [selectedDocument, setSelectedDocument] = useState<Document | null>(null);
    const [activeTab, setActiveTab] = useState<'gallery' | 'drive'>('drive');

    // Filter documents
    const filteredDocuments = documents.filter(doc => {
        const matchesSearch = 
            doc.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
            doc.author.toLowerCase().includes(searchQuery.toLowerCase()) ||
            doc.description.toLowerCase().includes(searchQuery.toLowerCase());
        
        const matchesCategory = selectedCategory === 'all' || doc.category === selectedCategory;
        
        return matchesSearch && matchesCategory;
    });

    return (
        <PublicLayout>
            <Head title="Documentos - Ser Ajayu" />

            {/* Hero Section */}
            <section className="relative py-16 lg:py-24 overflow-hidden">
                {/* Background */}
                <div className="absolute inset-0 -z-10">
                    <div className="absolute top-0 left-1/4 h-64 w-64 rounded-full bg-forest/10 blur-[100px]" />
                    <div className="absolute bottom-0 right-1/4 h-48 w-48 rounded-full bg-ochre/10 blur-[80px]" />
                </div>

                <div className="container mx-auto px-4">
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.6 }}
                        className="max-w-3xl"
                    >
                        {/* Breadcrumb */}
                        <nav className="flex items-center gap-2 text-sm text-muted-foreground mb-6">
                            <Link href="/" className="hover:text-foreground transition-colors">Inicio</Link>
                            <ChevronRight className="h-4 w-4" />
                            <span className="text-foreground">Documentos</span>
                        </nav>

                        <div className="flex items-center gap-4 mb-4">
                            <div className="p-3 rounded-2xl bg-forest/10">
                                <BookOpen className="h-8 w-8 text-forest" />
                            </div>
                            <div>
                                <h1 className="text-3xl lg:text-4xl font-bold text-foreground">
                                    Repositorio de Documentos
                                </h1>
                            </div>
                        </div>
                        <p className="text-lg text-muted-foreground mt-4 leading-relaxed">
                            Biblioteca virtual con documentos sobre etnofarmacología, protocolos de salud mental,
                            prácticas ancestrales y más. Explora y descarga recursos para la investigación.
                        </p>
                    </motion.div>
                </div>
            </section>

            {/* Filters & Content */}
            <section className="pb-24">
                <div className="container mx-auto px-4">


                    {/* Toolbar & Tabs Container */}
                    <div className="flex flex-col gap-6 mb-8">
                        {/* Top Bar: Search & Tabs */}
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.2 }}
                            className="flex flex-col lg:flex-row gap-4 justify-between items-start lg:items-center"
                        >
                             {/* Tabs Navigation (Moved here) */}
                             <div className="inline-flex items-center p-1 rounded-xl bg-muted/50 border border-border/50 shadow-sm shrink-0 self-end lg:self-auto order-1 lg:order-2">
                                <button
                                    onClick={() => setActiveTab('gallery')}
                                    className={cn(
                                        "flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200",
                                        activeTab === 'gallery'
                                            ? "bg-background text-foreground shadow-sm ring-1 ring-border/50"
                                            : "text-muted-foreground hover:text-foreground hover:bg-background/50"
                                    )}
                                >
                                    <Grid3X3 className="h-4 w-4" />
                                    Galería
                                </button>
                                <button
                                    onClick={() => setActiveTab('drive')}
                                    className={cn(
                                        "flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200",
                                        activeTab === 'drive'
                                            ? "bg-background text-foreground shadow-sm ring-1 ring-border/50"
                                            : "text-muted-foreground hover:text-foreground hover:bg-background/50"
                                    )}
                                >
                                    <HardDrive className="h-4 w-4" />
                                    Drive
                                </button>
                            </div>

                            {/* Search & Filters */}
                            <div className="flex flex-col sm:flex-row gap-4 w-full lg:w-auto flex-1 order-2 lg:order-1">
                                {/* Search */}
                                <div className="relative flex-1 max-w-md">
                                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                                    <Input
                                        type="search"
                                        placeholder="Buscar documentos..."
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="pl-10 bg-background"
                                    />
                                </div>

                                {/* Category filter */}
                                <Select 
                                    value={selectedCategory} 
                                    onValueChange={(value) => setSelectedCategory(value as DocumentCategory | 'all')}
                                >
                                    <SelectTrigger className="w-full sm:w-[200px] bg-background">
                                        <Filter className="h-4 w-4 mr-2" />
                                        <SelectValue placeholder="Categoría" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {categories.map((cat) => (
                                            <SelectItem key={cat.value} value={cat.value}>
                                                {cat.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>

                                {/* View Mode (Only visible in Gallery tab) */}
                                {activeTab === 'gallery' && (
                                    <div className="flex items-center gap-1 p-1 bg-muted rounded-lg shrink-0">
                                        <Button
                                            variant={viewMode === 'grid' ? 'secondary' : 'ghost'}
                                            size="icon"
                                            onClick={() => setViewMode('grid')}
                                            className={cn(
                                                viewMode === 'grid' && 'bg-background shadow-sm'
                                            )}
                                            title="Cuadrícula"
                                        >
                                            <Grid3X3 className="h-4 w-4" />
                                        </Button>
                                        <Button
                                            variant={viewMode === 'list' ? 'secondary' : 'ghost'}
                                            size="icon"
                                            onClick={() => setViewMode('list')}
                                            className={cn(
                                                viewMode === 'list' && 'bg-background shadow-sm'
                                            )}
                                            title="Lista"
                                        >
                                            <List className="h-4 w-4" />
                                        </Button>
                                    </div>
                                )}
                            </div>
                        </motion.div>
                    </div>

                    {activeTab === 'gallery' ? (
                        <>

                    {/* Results count */}
                    <motion.p
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        transition={{ delay: 0.3 }}
                        className="text-sm text-muted-foreground mb-6"
                    >
                        {filteredDocuments.length} documento{filteredDocuments.length !== 1 ? 's' : ''} encontrado{filteredDocuments.length !== 1 ? 's' : ''}
                    </motion.p>

                    {/* Documents grid/list */}
                    <motion.div
                        variants={staggerContainer}
                        initial="hidden"
                        animate="visible"
                        className={cn(
                            viewMode === 'grid' 
                                ? 'grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
                                : 'flex flex-col gap-4'
                        )}
                    >
                        {filteredDocuments.map((doc) => (
                            <DocumentCard 
                                key={doc.id} 
                                document={doc} 
                                viewMode={viewMode}
                                onSelect={() => setSelectedDocument(doc)}
                            />
                        ))}
                    </motion.div>

                            {/* Empty state */}
                            {filteredDocuments.length === 0 && (
                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    className="text-center py-16"
                                >
                                    <Folder className="h-16 w-16 text-muted-foreground/50 mx-auto mb-4" />
                                    <h3 className="text-lg font-semibold text-foreground mb-2">
                                        No se encontraron documentos
                                    </h3>
                                    <p className="text-muted-foreground">
                                        Intenta con otros términos de búsqueda o cambia los filtros.
                                    </p>
                                </motion.div>
                            )}
                        </>
                    ) : (
                        <motion.div
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            className="w-full"
                        >
                            <div className="bg-background rounded-2xl border border-border shadow-sm overflow-hidden h-[800px] relative">
                                <div className="absolute inset-0 flex items-center justify-center bg-muted/20 -z-10">
                                    <p className="text-muted-foreground animate-pulse">Cargando Google Drive...</p>
                                </div>
                                <iframe
                                    src="https://drive.google.com/embeddedfolderview?id=1oob8NQHqUlBxZRTX8g8PDI7xkRVjxsn2&usp=sharing#grid"
                                    width="100%"
                                    height="100%"
                                    style={{ border: 'none' }}
                                    title="Repositorio Google Drive"
                                    allowFullScreen
                                ></iframe>
                            </div>
                            
                            <div className="flex flex-col items-center justify-center gap-2 mt-6">
                                <p className="text-sm text-muted-foreground text-center max-w-lg mb-2">
                                    Si no puedes visualizar los documentos aquí, es posible que tu navegador esté bloqueando cookies de terceros.
                                </p>
                                <a 
                                    href="https://drive.google.com/drive/folders/1oob8NQHqUlBxZRTX8g8PDI7xkRVjxsn2?usp=sharing"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    <Button variant="outline" className="gap-2">
                                        <ExternalLink className="h-4 w-4" />
                                        Abrir directamente en Google Drive
                                    </Button>
                                </a>
                            </div>
                        </motion.div>
                    )}
                </div>
            </section>

            {/* Document Preview Modal */}
            <Dialog open={!!selectedDocument} onOpenChange={(open) => !open && setSelectedDocument(null)}>
                <DialogContent className="max-w-4xl h-[80vh] p-0 overflow-hidden flex flex-col bg-background">
                    <DialogHeader className="px-6 py-4 border-b border-border shrink-0">
                        <DialogTitle className="max-w-[90%] truncate">
                            {selectedDocument?.title}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="flex-1 w-full bg-muted/20 relative">
                        {selectedDocument && (
                            <iframe 
                                src={selectedDocument.driveUrl.replace('/view?usp=sharing', '/preview').replace('/edit?usp=sharing', '/preview')}
                                className="w-full h-full border-0 absolute inset-0"
                                allow="autoplay"
                            ></iframe>
                        )}
                    </div>
                    <div className="p-4 border-t border-border flex justify-between items-center bg-muted/10 shrink-0">
                        <div className="text-xs text-muted-foreground">
                            {selectedDocument?.category && categoryLabels[selectedDocument.category]} • {selectedDocument?.author}
                        </div>
                        <a 
                            href={selectedDocument?.driveUrl} 
                            target="_blank" 
                            rel="noopener noreferrer"
                        >
                            <Button size="sm" className="gap-2">
                                <Download className="h-4 w-4" />
                                Abrir en Drive
                            </Button>
                        </a>
                    </div>
                </DialogContent>
            </Dialog>
        </PublicLayout>
    );
}

