import React, { useState } from 'react';
import { X, Upload, FileText, Image, AlertCircle } from 'lucide-react';

const FileUpload = ({
  file,
  onUpload,
  onCancel,
  conversationId,
  senderId,
  maxSize = 10 * 1024 * 1024, // 10MB par défaut
}) => {
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState(null);

  // Vérifier le type de fichier et obtenir l'icône appropriée
  const getFileIcon = (fileType) => {
    if (fileType.startsWith('image/')) {
      return <Image className="w-8 h-8 text-blue-500" alt="Icône image" />;
    }
    return <FileText className="w-8 h-8 text-gray-500" alt="Icône fichier" />;
  };

  // Formater la taille du fichier
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // Vérifier si le fichier est valide
  const isValidFile = () => {
    const allowedTypes = [
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/webp',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'text/plain',
    ];

    if (!allowedTypes.includes(file.type)) {
      return false;
    }

    if (file.size > maxSize) {
      return false;
    }

    return true;
  };

  // Gérer l'upload
  const handleUpload = async () => {
    if (!isValidFile()) {
      setError('Type de fichier non autorisé ou fichier trop volumineux');
      return;
    }

    setIsUploading(true);
    setError(null);

    try {
      const result = await onUpload(
        file,
        conversationId,
        senderId,
        setUploadProgress
      );
      // L'upload s'est bien passé, le parent gère la suite
    } catch (error) {
      setError(error.message || "Erreur lors de l'upload");
      setIsUploading(false);
    }
  };

  if (!file) return null;

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4 shadow-lg">
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center space-x-3">
          {getFileIcon(file.type)}
          <div>
            <p className="font-medium text-gray-900 truncate max-w-xs">
              {file.name}
            </p>
            <p className="text-sm text-gray-500">{formatFileSize(file.size)}</p>
          </div>
        </div>
        <button
          onClick={onCancel}
          disabled={isUploading}
          className="text-gray-400 hover:text-gray-600 disabled:opacity-50"
        >
          <X className="w-5 h-5" />
        </button>
      </div>

      {/* Prévisualisation pour les images */}
      {file.type.startsWith('image/') && (
        <div className="mb-3">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={URL.createObjectURL(file)}
            alt="Aperçu du fichier sélectionné"
            className="max-w-full h-32 object-cover rounded-lg"
          />
        </div>
      )}

      {/* Validation du fichier */}
      {!isValidFile() && (
        <div className="mb-3 p-2 bg-red-50 border border-red-200 rounded-lg flex items-center space-x-2">
          <AlertCircle className="w-4 h-4 text-red-500" />
          <span className="text-sm text-red-700">
            {file.size > maxSize
              ? `Fichier trop volumineux (max ${formatFileSize(maxSize)})`
              : 'Type de fichier non autorisé'}
          </span>
        </div>
      )}

      {/* Erreur d'upload */}
      {error && (
        <div className="mb-3 p-2 bg-red-50 border border-red-200 rounded-lg flex items-center space-x-2">
          <AlertCircle className="w-4 h-4 text-red-500" />
          <span className="text-sm text-red-700">{error}</span>
        </div>
      )}

      {/* Barre de progression */}
      {isUploading && (
        <div className="mb-3">
          <div className="flex justify-between items-center mb-1">
            <span className="text-sm text-gray-600">Upload en cours...</span>
            <span className="text-sm text-gray-600">
              {Math.round(uploadProgress)}%
            </span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div
              className="bg-blue-500 h-2 rounded-full transition-all duration-300"
              style={{ width: `${uploadProgress}%` }}
            />
          </div>
        </div>
      )}

      {/* Boutons d'action */}
      <div className="flex justify-end space-x-2">
        <button
          onClick={onCancel}
          disabled={isUploading}
          className="px-3 py-2 text-sm text-gray-600 hover:text-gray-800 disabled:opacity-50"
        >
          Annuler
        </button>
        <button
          onClick={handleUpload}
          disabled={isUploading || !isValidFile()}
          className="flex items-center space-x-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Upload className="w-4 h-4" />
          <span>{isUploading ? 'Upload...' : 'Envoyer'}</span>
        </button>
      </div>
    </div>
  );
};

export default FileUpload;
