All files / varjoliitokauppa/components ImageUpload.tsx

28.33% Statements 17/60
37.93% Branches 11/29
31.25% Functions 5/16
28.57% Lines 16/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                        5x         1x 1x 1x 1x   1x         1x         1x                         1x                     1x                                                                                   1x 1x 1x     1x                   1x                     1x                                                                                                                                                                                                                
'use client';
 
import { useState, useRef } from 'react';
import Image from 'next/image';
import { Upload, X, Image as ImageIcon } from 'lucide-react';
 
interface ImageUploadProps {
  images: string[];
  onImagesChange: (images: string[]) => void;
  maxImages?: number;
}
 
export const ImageUpload: React.FC<ImageUploadProps> = ({
  images,
  onImagesChange,
  maxImages = 10
}) => {
  const [isDragging, setIsDragging] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<{ [key: string]: number }>({});
  const fileInputRef = useRef<HTMLInputElement>(null);
 
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };
 
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };
 
  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
 
    const files = Array.from(e.dataTransfer.files).filter((file: File) =>
      file.type.startsWith('image/')
    );
 
    if (files.length > 0) {
      await uploadFiles(files as File[]);
    }
  };
 
  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []) as File[];
    if (files.length > 0) {
      await uploadFiles(files);
    }
    // Reset input
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };
 
  const uploadFiles = async (files: File[]) => {
    if (images.length + files.length > maxImages) {
      alert(`Maksimi ${maxImages} kuvaa sallittu`);
      return;
    }
 
    setUploading(true);
    const newImages: string[] = [];
 
    for (const file of files) {
      try {
        setUploadProgress(prev => ({ ...prev, [file.name]: 0 }));
 
        const formData = new FormData();
        formData.append('file', file);
 
        const res = await fetch('/api/admin/upload', {
          method: 'POST',
          body: formData,
        });
 
        setUploadProgress(prev => ({ ...prev, [file.name]: 50 }));
 
        const data = await res.json();
 
        if (data.url) {
          newImages.push(data.url);
          setUploadProgress(prev => ({ ...prev, [file.name]: 100 }));
        } else if (data.error) {
          alert(`Virhe ladattaessa ${file.name}: ${data.error}`);
        }
      } catch (error) {
        console.error('Upload error:', error);
        alert(`Virhe ladattaessa ${file.name}`);
      }
    }
 
    onImagesChange([...images, ...newImages]);
    setUploading(false);
    setUploadProgress({});
  };
 
  const removeImage = (index: number) => {
    const newImages = images.filter((_, i) => i !== index);
    onImagesChange(newImages);
  };
 
  return (
    <div className="space-y-4">
      <label className="block text-sm font-medium mb-2">
        Kuvat ({images.length}/{maxImages})
      </label>
 
      {/* Image Preview Grid */}
      {images.length > 0 && (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 mb-4">
          {images.map((img, idx) => (
            <div key={idx} className="relative group">
              <div className="relative w-full h-32 overflow-hidden rounded-lg border-2 border-gray-200">
                <Image
                  src={img}
                  alt={`Product ${idx + 1}`}
                  fill
                  sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
                  className="object-cover"
                />
              </div>
              <button
                onClick={() => removeImage(idx)}
                className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                type="button"
              >
                <X size={16} />
              </button>
              {idx === 0 && (
                <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white text-xs py-1 px-2 rounded-b-lg text-center">
                  Pääkuva
                </div>
              )}
            </div>
          ))}
        </div>
      )}
 
      {/* Upload Progress */}
      {Object.keys(uploadProgress).length > 0 && (
        <div className="space-y-2">
          {Object.entries(uploadProgress).map(([name, progress]) => (
            <div key={name} className="flex items-center gap-2">
              <div className="flex-1 bg-gray-200 rounded-full h-2">
                <div
                  className="bg-black h-2 rounded-full transition-all"
                  style={{ width: `${progress}%` }}
                />
              </div>
              <span className="text-xs text-gray-600">{Math.round(progress)}%</span>
            </div>
          ))}
        </div>
      )}
 
      {/* Drag & Drop Area */}
      {images.length < maxImages && (
        <div
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          onClick={() => fileInputRef.current?.click()}
          className={`
            border-2 border-dashed rounded-xl p-8 text-center cursor-pointer
            transition-all duration-200
            ${isDragging
              ? 'border-black bg-gray-50 scale-105'
              : 'border-gray-300 hover:border-gray-400 hover:bg-gray-50'
            }
            ${uploading ? 'opacity-50 cursor-not-allowed' : ''}
          `}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            multiple
            onChange={handleFileSelect}
            className="hidden"
            disabled={uploading}
          />
 
          <div className="flex flex-col items-center gap-3">
            {uploading ? (
              <>
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-black"></div>
                <p className="text-sm text-gray-600">Ladataan kuvia...</p>
              </>
            ) : (
              <>
                <div className="bg-gray-100 p-4 rounded-full">
                  <Upload size={32} className="text-gray-600" />
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-900">
                    Raahaa kuvia tähän tai klikkaa valitaksesi
                  </p>
                  <p className="text-xs text-gray-500 mt-1">
                    PNG, JPG, GIF, WEBP (max 5MB per kuva)
                  </p>
                  <p className="text-xs text-gray-400 mt-1">
                    Voit valita useita kuvia kerralla
                  </p>
                </div>
              </>
            )}
          </div>
        </div>
      )}
 
      {/* Tips */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
        <div className="flex gap-2">
          <ImageIcon size={16} className="text-blue-600 mt-0.5 flex-shrink-0" />
          <div className="text-xs text-blue-800">
            <p className="font-medium">Vinkit:</p>
            <ul className="mt-1 space-y-1 list-disc list-inside">
              <li>Ensimmäinen kuva näytetään pääkuvana</li>
              <li>Suositellaan vähintään 800x800px kokoa</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};