import { useState } from "react";
import axios from "axios";

export const useS3Upload = () => {
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);
  const [isUploading, setIsUploading] = useState(false);

  const uploadS3FilesAPI = async (formData) => {
    setIsUploading(true);
    setProgress(0);
    setError(null);

    try {
      const uri = `https://app.equalityrecords.com/v2/api/lambda/s3/uploads/only/public`;
      const res = await axios.post(uri, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          "x-project":
            "ZXF1YWxpdHlyZWNvcmQ6cDV3YjJnd2M5aWVyZjhzem5ldDZibnNjcTA3bnVyYQ==",
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          setProgress(percentCompleted);
        },
      });

      setIsUploading(false);
      return res.data;
    } catch (error) {
      setError(error);
      setIsUploading(false);
      throw error;
    }
  };

  return { uploadS3FilesAPI, progress, error, isUploading };
};
