import { Spin, Typography } from "antd";
import * as React from "react";
import { useNavigate } from "react-router-dom";
import {
  HttpMethod,
  HttpRepository,
  HttpRoute,
} from "../../core/repository/http_repository";
import { pathStabilityScreen } from "../stability_preview/stability_preview";

const { Title } = Typography;

export const createProjectRoute = "/new_project";
 
const UploadButton = () => {
  const navigate = useNavigate();
  const [isLoading, setLoading] = React.useState<boolean>(false);

  const handleImageChange = function (e: React.ChangeEvent<HTMLInputElement>) {
    const fileList = e.target.files;

    if (!fileList) return;

    let file = fileList[0] as File;
    uploadFile(file);
  };
 
  const uploadFile = async (file: File) => {
    if (file) {
      const formData = new FormData();
      formData.append("freecad", file, file.name);
      setLoading(true);
      await HttpRepository.request(
        HttpMethod.POST,
        HttpRoute.createProject,
        formData
      );
      setLoading(false);
      navigate(pathStabilityScreen)
    }
  };
  return isLoading ? (
    <>
      <Spin />
    </>
  ) : (
    <label htmlFor="photo">
      <input
        accept="*/.FCStd"
        style={{ display: "none" }}
        id="photo"
        name="photo"
        type="file"
        multiple={false}
        onChange={handleImageChange}
      />
      Choose Cad file
    </label>
  );
};
export default function CreateProject() {
  return (
    <div className="centeredContainer">
      <div className="centeredDiv">
        <Title>Create new project</Title>
      </div>
      <div style={{ paddingTop: "10px" }}>
        <UploadButton />
      </div>
    </div>
  );
}
