File size: 7,450 Bytes
f4854a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { HiUpload, HiX, HiPhotograph, HiDocumentText, HiCheckCircle, HiExclamationCircle } from 'react-icons/hi';
import { HiArrowPath } from 'react-icons/hi2';
import api from '../../services/api';
import './FileUpload.css';

/**
 * Reusable drag-and-drop file upload component.
 *
 * Props:
 *   category    {string}   β€” storage category: 'profiles' | 'campaigns' | 'gallery' | 'stories' | 'blog' | 'help-requests'
 *   entityId    {string}   β€” optional related entity ID
 *   accept      {string}   β€” MIME types for the file input (e.g. "image/*" or "image/*,application/pdf")
 *   label       {string}   β€” label shown in the drop zone
 *   maxMB       {number}   β€” client-side file size hint (just for UI; server validates too)
 *   currentUrl  {string}   β€” existing file URL to show as preview
 *   onUpload    {function} β€” callback(url, key) called on successful upload
 *   onDelete    {function} β€” callback(key) called when user removes the file
 *   multiple    {boolean}  β€” allow multiple file selection
 *   className   {string}   β€” extra class for the root element
 */
export default function FileUpload({
  category,
  entityId = '',
  accept = 'image/*',
  label = 'Upload a file',
  maxMB = 5,
  currentUrl = '',
  onUpload,
  onDelete,
  multiple = false,
  className = '',
}) {
  const [isDragging, setIsDragging]   = useState(false);
  const [uploading, setUploading]     = useState(false);
  const [progress, setProgress]       = useState(0);
  const [error, setError]             = useState('');
  const [preview, setPreview]         = useState(currentUrl);
  const [uploadedKey, setUploadedKey] = useState('');

  const isImage = (file) => file?.type?.startsWith('image/');

  const handleFiles = useCallback(async (files) => {
    if (!files || files.length === 0) return;
    const file = files[0];  // handle first file (multiple handled separately)

    setError('');
    setProgress(0);

    // Client-side size check
    const maxBytes = maxMB * 1024 * 1024;
    if (file.size > maxBytes) {
      setError(`File too large. Maximum size is ${maxMB}MB.`);
      return;
    }

    // Show local preview for images immediately
    if (isImage(file)) {
      const reader = new FileReader();
      reader.onload = (e) => setPreview(e.target.result);
      reader.readAsDataURL(file);
    }

    setUploading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('category', category);
      if (entityId) formData.append('entityId', entityId);

      // Use raw axios call for multipart + progress tracking
      // (api interceptor handles auth token)
      const result = await api.post('/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: (e) => {
          const pct = Math.round((e.loaded * 100) / (e.total || 1));
          setProgress(pct);
        },
      });

      const url = result.url || result.previewUrl || '';
      const key = result.key || '';

      setUploadedKey(key);
      if (url) setPreview(url);
      setProgress(100);

      onUpload?.(url, key, result);
    } catch (err) {
      setError(err.message || 'Upload failed. Please try again.');
      // Revert preview on failure
      setPreview(currentUrl);
    } finally {
      setUploading(false);
    }
  }, [category, entityId, maxMB, currentUrl, onUpload]);

  const handleRemove = useCallback(() => {
    const key = uploadedKey;
    setPreview('');
    setUploadedKey('');
    setError('');
    onDelete?.(key);
  }, [uploadedKey, onDelete]);

  // Drag events
  const onDragOver  = (e) => { e.preventDefault(); setIsDragging(true); };
  const onDragLeave = (e) => { e.preventDefault(); setIsDragging(false); };
  const onDrop      = (e) => {
    e.preventDefault();
    setIsDragging(false);
    handleFiles(e.dataTransfer.files);
  };

  const fileIcon = accept.includes('pdf') ? <HiDocumentText /> : <HiPhotograph />;

  return (
    <div className={`fu-root ${className}`}>
      <AnimatePresence mode="wait">
        {preview ? (
          /* ── Preview State ── */
          <motion.div
            key="preview"
            className="fu-preview"
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
          >
            {isImage({ type: accept.startsWith('image') ? 'image/jpeg' : '' }) || preview.match(/\.(jpg|jpeg|png|webp|gif)(\?|$)/i) ? (
              <img src={preview} alt="Upload preview" className="fu-preview__img" />
            ) : (
              <div className="fu-preview__doc">
                <HiDocumentText className="fu-preview__doc-icon" />
                <span>File uploaded</span>
              </div>
            )}
            <button
              type="button"
              className="fu-preview__remove"
              onClick={handleRemove}
              title="Remove file"
            >
              <HiX />
            </button>
            <div className="fu-preview__success">
              <HiCheckCircle /> Uploaded
            </div>
          </motion.div>
        ) : (
          /* ── Drop Zone ── */
          <motion.label
            key="dropzone"
            className={`fu-zone ${isDragging ? 'fu-zone--dragging' : ''} ${uploading ? 'fu-zone--uploading' : ''}`}
            onDragOver={onDragOver}
            onDragLeave={onDragLeave}
            onDrop={onDrop}
            whileHover={{ scale: 1.01 }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            <input
              type="file"
              accept={accept}
              multiple={multiple}
              className="fu-input"
              onChange={(e) => handleFiles(e.target.files)}
              disabled={uploading}
            />

            <div className="fu-zone__icon">
              {uploading ? (
                <HiArrowPath className="spin-icon" />
              ) : isDragging ? (
                <HiUpload />
              ) : (
                fileIcon
              )}
            </div>

            <p className="fu-zone__label">
              {uploading ? 'Uploading…' : isDragging ? 'Drop to upload' : label}
            </p>
            <p className="fu-zone__hint">
              {uploading ? '' : `Drag & drop or click to browse Β· Max ${maxMB}MB`}
            </p>

            {/* Progress bar */}
            {uploading && (
              <div className="fu-progress">
                <motion.div
                  className="fu-progress__bar"
                  initial={{ width: 0 }}
                  animate={{ width: `${progress}%` }}
                  transition={{ ease: 'easeOut' }}
                />
                <span className="fu-progress__label">{progress}%</span>
              </div>
            )}
          </motion.label>
        )}
      </AnimatePresence>

      {/* Error message */}
      <AnimatePresence>
        {error && (
          <motion.p
            className="fu-error"
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0 }}
          >
            <HiExclamationCircle /> {error}
          </motion.p>
        )}
      </AnimatePresence>
    </div>
  );
}