File size: 9,249 Bytes
fee2f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
 * FileUploader component - Drag-and-drop file upload with progress
 */

import React, { useCallback, useState, useRef } from 'react';
import {
  Box,
  Typography,
  LinearProgress,
  Button,
  Alert,
  Paper,
} from '@mui/material';
import {
  CloudUpload as UploadIcon,
  Description as FileIcon,
  Close as CloseIcon,
} from '@mui/icons-material';

interface FileUploaderProps {
  onUpload: (file: File, taskType: string) => Promise<void>;
  onProgress?: (progress: number) => void;
  disabled?: boolean;
}

interface UploadState {
  file: File | null;
  progress: number;
  status: 'idle' | 'uploading' | 'success' | 'error';
  error: string | null;
}

const ACCEPTED_TYPES = ['.csv', '.json', '.xlsx', '.parquet'];
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB

const FileUploader: React.FC<FileUploaderProps> = ({
  onUpload,
  onProgress,
  disabled = false,
}) => {
  const [uploadState, setUploadState] = useState<UploadState>({
    file: null,
    progress: 0,
    status: 'idle',
    error: null,
  });
  const [isDragging, setIsDragging] = useState(false);
  const [taskType, setTaskType] = useState<'easy' | 'medium' | 'hard'>('easy');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const validateFile = (file: File): string | null => {
    const ext = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();
    if (!ACCEPTED_TYPES.includes(ext)) {
      return `Invalid file type. Accepted: ${ACCEPTED_TYPES.join(', ')}`;
    }
    if (file.size > MAX_FILE_SIZE) {
      return 'File size exceeds 100MB limit';
    }
    return null;
  };

  const handleFile = useCallback((file: File) => {
    const error = validateFile(file);
    if (error) {
      setUploadState({
        file: null,
        progress: 0,
        status: 'error',
        error,
      });
      return;
    }

    setUploadState({
      file,
      progress: 0,
      status: 'idle',
      error: null,
    });
  }, []);

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);

      if (disabled) return;

      const file = e.dataTransfer.files[0];
      if (file) {
        handleFile(file);
      }
    },
    [disabled, handleFile]
  );

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

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
        handleFile(file);
      }
    },
    [handleFile]
  );

  const handleUpload = async () => {
    if (!uploadState.file) return;

    setUploadState((prev) => ({ ...prev, status: 'uploading', progress: 0, error: null }));

    try {
      // Simulate progress for demo (in real app, use XMLHttpRequest upload events)
      const progressInterval = setInterval(() => {
        setUploadState((prev) => {
          if (prev.progress < 90) {
            const newProgress = prev.progress + Math.random() * 15;
            onProgress?.(Math.min(newProgress, 90));
            return { ...prev, progress: Math.min(newProgress, 90) };
          }
          return prev;
        });
      }, 200);

      await onUpload(uploadState.file, taskType);

      clearInterval(progressInterval);
      setUploadState((prev) => ({ ...prev, progress: 100, status: 'success' }));
      onProgress?.(100);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Upload failed';
      setUploadState((prev) => ({
        ...prev,
        status: 'error',
        error: errorMessage,
        progress: 0,
      }));
    }
  };

  const handleCancel = () => {
    setUploadState({
      file: null,
      progress: 0,
      status: 'idle',
      error: null,
    });
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  };

  return (
    <Box>
      {/* Drop Zone */}
      <Paper
        elevation={0}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        sx={{
          border: '2px dashed',
          borderColor: isDragging ? 'primary.main' : uploadState.error ? 'error.main' : 'grey.300',
          borderRadius: 2,
          p: 4,
          textAlign: 'center',
          bgcolor: isDragging ? 'action.hover' : 'background.paper',
          cursor: disabled ? 'not-allowed' : 'pointer',
          opacity: disabled ? 0.6 : 1,
          transition: 'all 0.2s ease',
          '&:hover': !disabled ? {
            borderColor: 'primary.main',
            bgcolor: 'action.hover',
          } : {},
        }}
        component="label"
      >
        <input
          ref={fileInputRef}
          type="file"
          hidden
          accept={ACCEPTED_TYPES.join(',')}
          onChange={handleInputChange}
          disabled={disabled}
        />

        <UploadIcon sx={{ fontSize: 48, color: 'primary.main', mb: 1 }} />
        <Typography variant="h6" gutterBottom>
          {isDragging ? 'Drop file here' : 'Drag & drop your file here'}
        </Typography>
        <Typography variant="body2" color="textSecondary">
          or click to browse
        </Typography>
        <Typography variant="caption" color="textSecondary" sx={{ display: 'block', mt: 1 }}>
          Supports: CSV, JSON, Excel, Parquet (max 100MB)
        </Typography>
      </Paper>

      {/* Selected File */}
      {uploadState.file && (
        <Box sx={{ mt: 2, p: 2, bgcolor: 'grey.50', borderRadius: 1 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <FileIcon color="primary" />
            <Box sx={{ flex: 1 }}>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                {uploadState.file.name}
              </Typography>
              <Typography variant="body2" color="textSecondary">
                {formatFileSize(uploadState.file.size)}
              </Typography>
            </Box>
            {uploadState.status === 'idle' && (
              <Button
                size="small"
                color="error"
                onClick={handleCancel}
                startIcon={<CloseIcon />}
              >
                Remove
              </Button>
            )}
          </Box>
        </Box>
      )}

      {/* Error Message */}
      {uploadState.error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {uploadState.error}
        </Alert>
      )}

      {/* Progress Bar */}
      {uploadState.status === 'uploading' && (
        <Box sx={{ mt: 2 }}>
          <LinearProgress variant="determinate" value={uploadState.progress} />
          <Typography variant="body2" color="textSecondary" sx={{ mt: 1 }}>
            Uploading... {Math.round(uploadState.progress)}%
          </Typography>
        </Box>
      )}

      {/* Success Message */}
      {uploadState.status === 'success' && (
        <Alert severity="success" sx={{ mt: 2 }}>
          File uploaded successfully!
        </Alert>
      )}

      {/* Task Selection & Upload Button */}
      {uploadState.file && uploadState.status !== 'uploading' && (
        <Box sx={{ mt: 3, display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
          <Box sx={{ minWidth: 200 }}>
            <Typography variant="body2" gutterBottom>
              <strong>Task Difficulty:</strong>
            </Typography>
            <Box sx={{ display: 'flex', gap: 1 }}>
              {(['easy', 'medium', 'hard'] as const).map((type) => (
                <Button
                  key={type}
                  variant={taskType === type ? 'contained' : 'outlined'}
                  size="small"
                  onClick={() => setTaskType(type)}
                  disabled={disabled}
                >
                  {type.charAt(0).toUpperCase() + type.slice(1)}
                </Button>
              ))}
            </Box>
          </Box>

          <Box sx={{ flex: 1 }} />

          <Button
            variant="contained"
            size="large"
            onClick={handleUpload}
            disabled={disabled || !uploadState.file}
            startIcon={<UploadIcon />}
          >
            Upload & Start Cleaning
          </Button>
        </Box>
      )}

      {/* Task Description */}
      {uploadState.file && uploadState.status !== 'uploading' && (
        <Box sx={{ mt: 2, p: 2, bgcolor: 'info.light', borderRadius: 1 }}>
          <Typography variant="body2">
            <strong>{taskType.charAt(0).toUpperCase() + taskType.slice(1)} task:</strong>{' '}
            {taskType === 'easy' && 'Handle missing values, duplicates, basic formatting'}
            {taskType === 'medium' && 'Easy + Outliers, category standardization'}
            {taskType === 'hard' && 'Medium + Complex patterns, custom rules, edge cases'}
          </Typography>
        </Box>
      )}
    </Box>
  );
};

export default FileUploader;