import { useLayoutEffect, useRef, useState } from "react";
import { downloadImportTemplate, uploadPointsFile } from "../../api.js";
import { Button, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import { download } from "../../utils.js";

export const LoadingStage = ({setFileId}) => {
  const ref = useRef(null);
  const [isClicked, setIsClicked] = useState(true);

  const onFileChange = async (options) => {
    const { onSuccess, onError, file, onProgress } = options;
    const config = {
      onUploadProgress: event => {
        const percent = Math.floor((event.loaded / event.total) * 100);
        onProgress({ percent });
      }
    };
    try {
      const {id} = await uploadPointsFile(file, config);
      onSuccess("Ok");
      setFileId(id);
    } catch (e) {
      //
    }
  };

  const onTemplateDownload = async () => {
    const data = await downloadImportTemplate();
    await download('template.xlsx', data);
  }

  useLayoutEffect(() => {
    if (ref && ref.current && !isClicked) {
      ref.current.click();
      setIsClicked(true);
    }
  }, [isClicked]);

  return (
    <>
      <Upload
        name='file'
        accept='application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'
        customRequest={onFileChange}
      >
        <Button icon={<UploadOutlined />}>Выбрать файл .xlsx</Button>
      </Upload>
      <Button className="p-0 text-xs text-grey underline" type="text" onClick={onTemplateDownload}>Скачать шаблон</Button>
    </>
  );
}