"use client";

import { useState } from "react";
import { Button, Typography, Box, LinearProgress } from "@mui/material";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { uploadFileAction } from "./upload-actions";

export default function UploadForm() {
  const [uploading, setUploading] = useState(false);

  async function handleAction(formData: FormData) {
    const file = formData.get("file") as File;
    if (!file || file.size === 0) return;

    setUploading(true);
    try {
      await uploadFileAction(formData);
      alert("Uploaded successfully!");
    } catch (error) {
      console.error(error);
      alert("Upload failed.");
    } finally {
      setUploading(false);
    }
  }

  return (
    <Box className="p-4 border-2 border-dashed border-gray-300 rounded-lg text-center">
      <form action={handleAction}>
        <input
          type="file"
          name="file"
          id="file-upload"
          className="hidden"
          onChange={(e) => {
             // Optional: Trigger auto-submit or show filename
          }}
        />
        <label htmlFor="file-upload">
          <Button
            variant="outlined"
            component="span"
            startIcon={<CloudUploadIcon />}
            disabled={uploading}
          >
            Select Book / File
          </Button>
        </label>
        
        {uploading && (
          <Box sx={{ width: '100%', mt: 2 }}>
            <Typography variant="caption">Uploading to OneDrive & Database...</Typography>
            <LinearProgress />
          </Box>
        )}
        
        <Box mt={2}>
          <Button type="submit" variant="contained" disabled={uploading}>
            Confirm Upload
          </Button>
        </Box>
      </form>
    </Box>
  );
}