import { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { Upload, X, Image as ImageIcon, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { useImageUpload } from '@/hooks/useImageUpload';
import { cn } from '@/lib/utils';

interface ImageUploaderProps {
  onUploadComplete: (urls: string[]) => void;
  maxFiles?: number;
  category?: string;
  className?: string;
  multiple?: boolean;
}

export const ImageUploader = ({
  onUploadComplete,
  maxFiles = 5,
  category,
  className,
  multiple = true,
}: ImageUploaderProps) => {
  const [previewUrls, setPreviewUrls] = useState<string[]>([]);
  const { uploadSingle, uploadMultiple, uploading, progress } = useImageUpload({ category });

  const onDrop = useCallback(
    async (acceptedFiles: File[]) => {
      // Create preview URLs
      const previews = acceptedFiles.map((file) => URL.createObjectURL(file));
      setPreviewUrls(previews);

      // Upload files
      if (multiple && acceptedFiles.length > 1) {
        const response = await uploadMultiple(acceptedFiles);
        if (response?.success) {
          const urls = response.uploads.map((upload) => upload.url);
          onUploadComplete(urls);
        } else {
          // Clear previews on error
          setPreviewUrls([]);
        }
      } else {
        const response = await uploadSingle(acceptedFiles[0]);
        if (response?.success) {
          onUploadComplete([response.url]);
        } else {
          // Clear previews on error
          setPreviewUrls([]);
        }
      }
    },
    [multiple, uploadSingle, uploadMultiple, onUploadComplete]
  );

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'image/jpeg': ['.jpg', '.jpeg'],
      'image/png': ['.png'],
      'image/webp': ['.webp'],
      'image/gif': ['.gif'],
    },
    maxFiles: multiple ? maxFiles : 1,
    multiple,
    disabled: uploading,
  });

  const removePreview = (index: number) => {
    setPreviewUrls((prev) => prev.filter((_, i) => i !== index));
  };

  return (
    <div className={cn('space-y-4', className)}>
      <div
        {...getRootProps()}
        className={cn(
          'border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors',
          isDragActive ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/50',
          uploading && 'pointer-events-none opacity-50'
        )}
      >
        <input {...getInputProps()} />
        <div className="flex flex-col items-center justify-center space-y-3">
          {uploading ? (
            <Loader2 className="w-12 h-12 text-primary animate-spin" />
          ) : (
            <Upload className="w-12 h-12 text-muted-foreground" />
          )}
          <div>
            <p className="text-sm font-medium">
              {isDragActive
                ? 'Suelta las imágenes aquí...'
                : 'Arrastra y suelta imágenes aquí, o haz clic para seleccionar'}
            </p>
            <p className="text-xs text-muted-foreground mt-1">
              JPG, PNG, WEBP, GIF hasta 5MB {multiple && `(máximo ${maxFiles} archivos)`}
            </p>
          </div>
        </div>
      </div>

      {uploading && (
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">Subiendo...</span>
            <span className="font-medium">{progress}%</span>
          </div>
          <Progress value={progress} />
        </div>
      )}

      {previewUrls.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {previewUrls.map((url, index) => (
            <div key={index} className="relative group aspect-square rounded-lg overflow-hidden bg-muted">
              <img src={url} alt={`Preview ${index + 1}`} className="w-full h-full object-cover" />
              {!uploading && (
                <Button
                  variant="destructive"
                  size="icon"
                  className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
                  onClick={() => removePreview(index)}
                >
                  <X className="w-4 h-4" />
                </Button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
