import S3 from 'react-aws-s3';

const config = {
  bucketName: process.env.REACT_APP_AWS_BUCKETNAME,
  dirName: process.env.REACT_APP_AWS_DIRNAME,
  region: process.env.REACT_APP_AWS_REGION,
  accessKeyId: process.env.REACT_APP_AWS_ACCESSKEYID,
  secretAccessKey: process.env.REACT_APP_AWS_SECRETACCESSKEY,
  s3Url: process.env.REACT_APP_AWS_S3URL
};

export const handleFileChange = async (event) => {
  console.log('imgfile', event.target.files[0]);
  const file = event.target.files[0];

  if (file) {
    const validTypes = ['image/png', 'image/jpeg', 'image/jpg'];
    if (validTypes.includes(file.type)) {
      const reader = new FileReader();

      reader.onload = (e) => {};

      reader.readAsDataURL(file);

      console.log('imagename', formatFileName(file.name));

      try {
        const ReactS3Client = new S3(config);
        const data = await ReactS3Client.uploadFile(file, file.name);

        if (data.status === 204) {
          console.log('Upload Success');
          console.log('final img s3', data);
          console.log('newimgurl', data.location);

          return data.location;
        } else {
          console.error('Failed to upload');
          return 'Failed to upload the file. Please try again.';
        }
      } catch (err) {
        console.error(err);

        return 'Failed to upload the file. Please try again.';
      }
    } else {
      return 'Please upload a valid PNG or JPEG image.';
    }
  }
};

const formatFileName = (name) => {
  const maxLength = 20; // Adjust this value as needed
  if (name.length > maxLength) {
    return `${name.substring(0, maxLength)}...`;
  }
  return name;
};
