import React, { useState } from 'react';
import { Button, LinearProgress, Box, Typography } from '@mui/material';
import { uploadFile } from '../services/fileService';

export const FileUpload: React.FC = () => {
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState('');

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

    try {
      setError('');
      await uploadFile(file, (progress) => setProgress(progress));
    } catch (err) {
      setError('Failed to upload file');
    }
  };

  return (
    <Box sx={{ width: '100%', mt: 2 }}>
      <input
        accept="*/*"
        style={{ display: 'none' }}
        id="raised-button-file"
        type="file"
        onChange={handleFileUpload}
      />
      <label htmlFor="raised-button-file">
        <Button variant="contained" component="span">
          Upload File
        </Button>
      </label>
      {progress > 0 && <LinearProgress variant="determinate" value={progress} sx={{ mt: 2 }} />}
      {error && <Typography color="error">{error}</Typography>}
    </Box>
  );
};