import { useState, useRef } from 'react';
import { uploadAvatar, deleteAvatar, AvatarUploadError } from '../services/avatarService';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/useToast';
import { Progress } from '@/components/feedback/Progress';

interface AvatarUploadProps {
  userId: number;
  currentAvatarUrl?: string;
  onAvatarUpdated?: (avatarUrl: string) => void;
}

export function AvatarUpload({ userId, currentAvatarUrl, onAvatarUpdated }: AvatarUploadProps) {
  const [preview, setPreview] = useState<string | null>(currentAvatarUrl || null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { toast } = useToast();

  const validateFile = (file: File): string | null => {
    // Valider format
    const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
      return 'Format non supporté. Utilisez JPEG, PNG ou WebP.';
    }
    
    // Valider taille (5MB)
    const maxSize = 5 * 1024 * 1024;
    if (file.size > maxSize) {
      return 'Fichier trop volumineux. Taille maximum: 5MB.';
    }
    
    return null;
  };

  const handleFileSelect = async (file: File) => {
    const error = validateFile(file);
    if (error) {
      toast.error(error);
      return;
    }
    
    // Afficher preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setPreview(reader.result as string);
    };
    reader.readAsDataURL(file);
    
    // Upload
    setIsUploading(true);
    setUploadProgress(0);
    try {
      const response = await uploadAvatar(userId, file, (progress) => {
        setUploadProgress(progress);
      });
      setPreview(response.avatar_url);
      onAvatarUpdated?.(response.avatar_url);
      toast.success('Avatar mis à jour avec succès');
    } catch (error) {
      if (error instanceof AvatarUploadError) {
        switch (error.code) {
          case 'VALIDATION':
            toast.error(error.message);
            break;
          case 'NETWORK':
            toast.error(error.message);
            break;
          case 'SERVER':
            toast.error(error.message);
            break;
          default:
            toast.error('Erreur lors de l\'upload');
        }
      } else {
        toast.error('Erreur lors de l\'upload de l\'avatar');
      }
      setPreview(currentAvatarUrl || null);
    } finally {
      setIsUploading(false);
      setUploadProgress(0);
    }
  };

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    
    const file = e.dataTransfer.files[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDelete = async () => {
    try {
      await deleteAvatar(userId);
      setPreview(null);
      onAvatarUpdated?.('');
      toast.success('Avatar supprimé');
    } catch (error) {
      toast.error('Erreur lors de la suppression de l\'avatar');
    }
  };

  return (
    <div className="flex flex-col items-center gap-4">
      <div
        className={`relative w-32 h-32 rounded-full border-2 border-dashed ${
          isDragging ? 'border-blue-500' : 'border-gray-300'
        } cursor-pointer overflow-hidden`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={() => fileInputRef.current?.click()}
      >
        {preview ? (
          <img src={preview} alt="Avatar" className="w-full h-full object-cover" />
        ) : (
          <div className="w-full h-full flex items-center justify-center bg-gray-100">
            <span className="text-gray-400 text-sm">Cliquez pour uploader</span>
          </div>
        )}
        {isUploading && (
          <div className="absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center">
            <Progress value={uploadProgress} className="w-24" showLabel />
            <div className="text-white text-sm mt-2">{uploadProgress}%</div>
          </div>
        )}
      </div>
      
      <input
        ref={fileInputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        onChange={handleFileInputChange}
        className="hidden"
      />
      
      <div className="flex gap-2">
        <Button onClick={() => fileInputRef.current?.click()} disabled={isUploading} size="sm">
          Changer
        </Button>
        {preview && (
          <Button variant="destructive" onClick={handleDelete} disabled={isUploading} size="sm">
            Supprimer
          </Button>
        )}
      </div>
    </div>
  );
}

