import React from "react";
import { GlobalContext, showToast } from "Src/globalContext";

const FileUpload = ({
  maxFileSize = 500,

  fileValues,
  setFileValues,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [maxFileSizeStr, setMaxFileSizeStr] = React.useState(
    `${maxFileSize}MB`
  );

  const convertMBToGB = (mb) => {
    return {
      value: mb / 1024,
      unit: "GB",
    };
  };

  const saveFiles = (e) => {
    const files = e.target.files;

    if (files.length > 0) {
      setFileValues([...fileValues, ...files]);
    }
  };

  const validateFileSize = (file) => {
    const fileSize = file.size / 1024 / 1024; // in MB
    if (fileSize > maxFileSize) {
      showToast(
        globalDispatch,
        `File size exceeds ${maxFileSize}MB. Please upload a smaller file.`,
        5000,
        "error"
      );
      return false;
    }
    return true;
  };

  React.useEffect(() => {
    if (maxFileSize > 1024) {
      const { value, unit } = convertMBToGB(maxFileSize);
      let maxFileSizeStr = `${value}${unit}`;
      setMaxFileSizeStr(maxFileSizeStr);
    }
  }, [maxFileSize]);

  React.useEffect(() => {
    if (maxFileSize > 1024) {
      const { value, unit } = convertMBToGB(maxFileSize);
      let maxFileSizeStr = `${value}${unit}`;
      setMaxFileSizeStr(maxFileSizeStr);
    }
  }, [maxFileSize]);
  return (
    <>
      <div className="mt-1 flex h-[45px] w-full items-center rounded border-2 border-form-strokedark bg-form-input">
        <div className="flex h-full min-w-max items-center justify-center px-3">
          Choose File
        </div>
        <input
          onChange={saveFiles}
          type="file"
          accept=".txt,.json,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, audio/*"
          required
          className="block w-full border-transparent bg-transparent py-2 pl-3 text-white outline-none placeholder:text-gray-500 focus:ring-0 focus-visible:outline-transparent"
          placeholder="No File Choosen"
        />
      </div>

      <div className="mb-2 text-xs text-gray-100">
        Maximum file size: {maxFileSizeStr}
      </div>
    </>
  );
};

export default FileUpload;
