import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Upload, X, Loader2, Image as ImageIcon } from "lucide-react";
import { toast } from "sonner";

interface ImageUploadProps {
  label: string;
  currentImageUrl?: string | null;
  onUploadComplete: (url: string, s3Key: string) => void;
  accept?: string;
  maxSizeMB?: number;
}

export default function ImageUpload({
  label,
  currentImageUrl,
  onUploadComplete,
  accept = "image/png,image/jpeg,image/jpg",
  maxSizeMB = 5,
}: ImageUploadProps) {
  const [uploading, setUploading] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string | null>(currentImageUrl || null);
  const fileInputRef = useRef<HTMLInputElement>(null);

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

    // Vérifier la taille du fichier
    const fileSizeMB = file.size / (1024 * 1024);
    if (fileSizeMB > maxSizeMB) {
      toast.error(`Le fichier est trop volumineux (max ${maxSizeMB}MB)`);
      return;
    }

    // Vérifier le type de fichier
    if (!file.type.startsWith("image/")) {
      toast.error("Veuillez sélectionner une image");
      return;
    }

    setUploading(true);

    try {
      // Créer un aperçu local
      const localPreview = URL.createObjectURL(file);
      setPreviewUrl(localPreview);

      // Préparer les données pour l'upload
      const formData = new FormData();
      formData.append("file", file);

      // Envoyer le fichier au serveur
      const response = await fetch("/api/upload-image", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("Erreur lors de l'upload");
      }

      const data = await response.json();

      if (data.success && data.url && data.s3Key) {
        toast.success("Image uploadée avec succès");
        setPreviewUrl(data.url);
        onUploadComplete(data.url, data.s3Key);
      } else {
        throw new Error(data.message || "Erreur lors de l'upload");
      }
    } catch (error) {
      console.error("Erreur upload:", error);
      toast.error("Erreur lors de l'upload de l'image");
      setPreviewUrl(currentImageUrl || null);
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const handleRemove = () => {
    setPreviewUrl(null);
    onUploadComplete("", "");
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  return (
    <div className="space-y-2">
      <Label>{label}</Label>
      
      <div className="flex items-start gap-4">
        {/* Aperçu de l'image */}
        <div className="flex-shrink-0">
          {previewUrl ? (
            <div className="relative group">
              <img
                src={previewUrl}
                alt="Aperçu"
                className="w-32 h-32 object-contain border rounded-lg bg-gray-50"
              />
              <Button
                type="button"
                variant="destructive"
                size="icon"
                className="absolute -top-2 -right-2 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                onClick={handleRemove}
                disabled={uploading}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          ) : (
            <div className="w-32 h-32 border-2 border-dashed rounded-lg flex items-center justify-center bg-gray-50">
              <ImageIcon className="h-8 w-8 text-gray-400" />
            </div>
          )}
        </div>

        {/* Bouton d'upload */}
        <div className="flex-1 space-y-2">
          <input
            ref={fileInputRef}
            type="file"
            accept={accept}
            onChange={handleFileSelect}
            className="hidden"
            disabled={uploading}
          />
          <Button
            type="button"
            variant="outline"
            onClick={() => fileInputRef.current?.click()}
            disabled={uploading}
          >
            {uploading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Upload en cours...
              </>
            ) : (
              <>
                <Upload className="mr-2 h-4 w-4" />
                {previewUrl ? "Changer l'image" : "Sélectionner une image"}
              </>
            )}
          </Button>
          <p className="text-xs text-muted-foreground">
            Formats acceptés: PNG, JPG, JPEG (max {maxSizeMB}MB)
          </p>
        </div>
      </div>
    </div>
  );
}
