'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, ChevronLeft, ChevronRight, Download, FileText, Image as ImageIcon } from 'lucide-react';

interface Adjunto {
    id: string;
    nombre: string;
    url: string;
    contentType: string | null;
    size: number | null;
}

interface Props {
    adjuntos: Adjunto[];
    initialIndex: number;
    onClose: () => void;
}

export default function AdjuntosViewer({ adjuntos, initialIndex, onClose }: Props) {
    const [currentIndex, setCurrentIndex] = useState(initialIndex);

    const handleNext = (e?: React.MouseEvent) => {
        if (e) {
            e.stopPropagation();
            e.preventDefault();
        }
        setCurrentIndex((prev) => (prev + 1) % adjuntos.length);
    };

    const handlePrev = (e?: React.MouseEvent) => {
        if (e) {
            e.stopPropagation();
            e.preventDefault();
        }
        setCurrentIndex((prev) => (prev - 1 + adjuntos.length) % adjuntos.length);
    };

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') onClose();
            if (e.key === 'ArrowRight') handleNext();
            if (e.key === 'ArrowLeft') handlePrev();
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [adjuntos.length, onClose]);

    const adjunto = adjuntos[currentIndex];
    if (!adjunto) return null;

    const fileExt = adjunto.nombre.toLowerCase().split('.').pop() || '';
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'];
    const isImage = adjunto.contentType?.startsWith('image/') || imageExtensions.includes(fileExt);
    const isPdf = adjunto.contentType === 'application/pdf' || fileExt === 'pdf';

    return (
        <AnimatePresence>
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 p-4 sm:p-8 backdrop-blur-sm"
                onClick={onClose}
            >
                {/* Superior toolbar */}
                <div
                    className="absolute top-0 left-0 right-0 flex items-center justify-between p-4 text-white z-[60] bg-gradient-to-b from-black/60 to-transparent"
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="flex items-center gap-3">
                        <span className="text-sm font-medium bg-black/60 px-3 py-1.5 rounded-full border border-white/20 shadow-sm">
                            {currentIndex + 1} de {adjuntos.length}
                        </span>
                        <span className="text-sm font-medium hidden sm:inline-block max-w-sm truncate">
                            {adjunto.nombre}
                        </span>
                    </div>
                    <div className="flex items-center gap-4">
                        <a
                            href={adjunto.url}
                            download={adjunto.nombre}
                            className="p-2 hover:bg-white/10 rounded-full transition-colors flex items-center gap-2"
                            title="Descargar archivo"
                            onClick={(e) => e.stopPropagation()}
                        >
                            <Download className="w-5 h-5" />
                        </a>
                        <button
                            onClick={(e) => { e.stopPropagation(); onClose(); }}
                            className="p-2 hover:bg-white/10 rounded-full transition-colors"
                            title="Cerrar visor"
                        >
                            <X className="w-6 h-6" />
                        </button>
                    </div>
                </div>

                {/* Controles de Carrusel */}
                {adjuntos.length > 1 && (
                    <>
                        <button
                            onClick={handlePrev}
                            className="absolute left-4 top-1/2 -translate-y-1/2 p-3 bg-white/10 hover:bg-white/20 text-white rounded-full transition-all z-[60] backdrop-blur-md"
                        >
                            <ChevronLeft className="w-8 h-8" />
                        </button>
                        <button
                            onClick={handleNext}
                            className="absolute right-4 top-1/2 -translate-y-1/2 p-3 bg-white/10 hover:bg-white/20 text-white rounded-full transition-all z-[60] backdrop-blur-md"
                        >
                            <ChevronRight className="w-8 h-8" />
                        </button>
                    </>
                )}

                {/* Content Viewer */}
                <div
                    className="relative w-full h-full max-w-6xl flex items-center justify-center z-50 pointer-events-none"
                    onClick={(e) => e.stopPropagation()}
                >
                    {isImage ? (
                        <motion.img
                            key={adjunto.id}
                            initial={{ opacity: 0, scale: 0.95 }}
                            animate={{ opacity: 1, scale: 1 }}
                            transition={{ duration: 0.2 }}
                            src={adjunto.url}
                            alt={adjunto.nombre}
                            className="max-w-full max-h-full object-contain rounded-lg shadow-2xl pointer-events-auto"
                        />
                    ) : isPdf ? (
                        <motion.iframe
                            key={adjunto.id}
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ duration: 0.2 }}
                            src={adjunto.url}
                            className="w-full h-full bg-white rounded-lg shadow-2xl pointer-events-auto"
                            title={adjunto.nombre}
                        />
                    ) : (
                        <motion.div
                            key={adjunto.id}
                            initial={{ opacity: 0, scale: 0.95 }}
                            animate={{ opacity: 1, scale: 1 }}
                            className="bg-white rounded-xl p-8 flex flex-col items-center justify-center max-w-md w-full text-center pointer-events-auto"
                        >
                            <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                <FileText className="w-10 h-10 text-gray-400" />
                            </div>
                            <h3 className="text-lg font-bold text-gray-900 mb-2 truncate w-full px-4">
                                {adjunto.nombre}
                            </h3>
                            <p className="text-sm text-gray-500 mb-6">
                                La vista previa no está disponible para este tipo de archivo.
                            </p>
                            <a
                                href={adjunto.url}
                                download={adjunto.nombre}
                                className="flex items-center gap-2 px-6 py-3 bg-[#1a365d] text-white rounded-lg hover:bg-[#2c5282] transition-colors font-medium"
                            >
                                <Download className="w-4 h-4" />
                                Descargar Archivo
                            </a>
                        </motion.div>
                    )}
                </div>
            </motion.div>
        </AnimatePresence>
    );
}
