import React, { useState, useEffect } from 'react';
import { X, Download, Loader2, ZoomIn, ZoomOut } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface PDFPreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  pdfUrl: string | null;
  fileName?: string;
}

const PDFPreviewModal: React.FC<PDFPreviewModalProps> = ({
  isOpen,
  onClose,
  pdfUrl,
  fileName = 'document.pdf'
}) => {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (pdfUrl) {
      setLoading(false);
    }
  }, [pdfUrl]);

  const handleDownload = () => {
    if (!pdfUrl) return;
    
    const a = document.createElement('a');
    a.href = pdfUrl;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    a.remove();
  };

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        {/* Backdrop */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
          className="fixed inset-0 bg-black/60 backdrop-blur-sm"
        />

        {/* Modal */}
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.95 }}
          className="relative bg-white dark:bg-gray-950 w-full max-w-6xl h-screen shadow-2xl flex flex-col overflow-hidden"
        >
          {/* Header */}
          <div className="flex-shrink-0 px-6 py-4 border-b border-gray-200 dark:border-gray-800 flex justify-between items-center bg-gray-50/50 dark:bg-gray-900/50">
            <div className="flex items-center gap-3">
              <h3 className="text-lg font-bold text-gray-900 dark:text-white">
                Prévisualisation PDF
              </h3>
              <span className="text-sm text-gray-500 dark:text-gray-400">
                {fileName}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={handleDownload}
                className="flex items-center gap-2 px-4 py-2 bg-[#941403] text-white rounded-xl text-sm font-medium hover:bg-[#7a1002] transition-colors"
              >
                <Download className="w-4 h-4" />
                Télécharger
              </button>
              <button
                onClick={onClose}
                className="p-2 hover:bg-gray-200 dark:hover:bg-gray-800 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
          </div>

          {/* PDF Viewer */}
          <div className="flex-1 overflow-hidden bg-gray-100 dark:bg-gray-900 relative">
            {loading && (
              <div className="absolute inset-0 flex items-center justify-center">
                <Loader2 className="w-8 h-8 text-[#941403] animate-spin" />
              </div>
            )}
            {pdfUrl && (
              <iframe
                src={pdfUrl}
                className="w-full h-full border-0"
                title="PDF Preview"
                onLoad={() => setLoading(false)}
              />
            )}
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  );
};


// =============================================
// Hook personnalisé pour gérer la prévisualisation PDF
// =============================================
export const usePDFPreview = () => {
  const [pdfUrl, setPdfUrl] = useState<string | null>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [fileName, setFileName] = useState('document.pdf');

  const openPreview = (blob: Blob, name?: string) => {
    // Révoquer l'ancienne URL si elle existe
    if (pdfUrl) {
      window.URL.revokeObjectURL(pdfUrl);
    }

    const url = window.URL.createObjectURL(blob);
    setPdfUrl(url);
    setFileName(name || 'document.pdf');
    setIsOpen(true);
  };

  const closePreview = () => {
    setIsOpen(false);
  };

  // Cleanup à la destruction du composant
  useEffect(() => {
    return () => {
      if (pdfUrl) {
        window.URL.revokeObjectURL(pdfUrl);
      }
    };
  }, [pdfUrl]);

  return {
    pdfUrl,
    isOpen,
    fileName,
    openPreview,
    closePreview,
    PDFPreviewModal,
  };
};

export default PDFPreviewModal;