import { useEffect, useState } from "@theia/core/shared/react";
import * as React from "react";
import { createUseStyles } from "react-jss";
import { LocalStorageKey, RCloneEndPoints } from "../../../../constants";
import fetchRClone from "../../../../helpers/fetchRClone";
import BackButton from "../../../BackButton";
import JobStatus from "../../../JobStatus";
import Stats from "../../../Stats";
import { useCommonStyles } from "../../StorjWidget.style";

const useStyles = createUseStyles({
  actionContainer: {
    display: "flex",
    alignItems: "center",
    marginBottom: 16,
    justifyContent: "space-between",
  },
});
type Props = {
  jobId?: number;
};
function JobStatusScreen(props: Props) {
  const { jobId: jobIdProp } = props;
  const [isCancelling, setIsCancelling] = useState<boolean>(false);
  const [jobId, setJobId] = useState<number | undefined>(jobIdProp);
  const classes = useStyles();
  const commonClasses = useCommonStyles();

  useEffect(() => {
    populateJobId();
  }, [jobIdProp]);
  const populateJobId = () => {
    if (jobIdProp) {
      return;
    }
    const selectedJob = localStorage.getItem(LocalStorageKey.SELECTED_JOB);
    selectedJob && setJobId(+selectedJob);
  };

  const handleClickCancelAction = async () => {
    setIsCancelling(true);
    const options = {
      body: JSON.stringify({
        jobid: jobId,
      }),
    };
    try {
      await fetchRClone(RCloneEndPoints.stopJob, options);
    } catch (error) {
      console.error(error);
    } finally {
      setIsCancelling(false);
    }
  };
  return (
    <div>
      <div className={classes.actionContainer}>
        <BackButton />
        <h4
          onClick={handleClickCancelAction}
          className={commonClasses.linkAction}
        >
          Cancel Action
          {isCancelling && (
            <i style={{ marginLeft: 8 }} className="fa fa-spinner fa-spin" />
          )}
        </h4>
      </div>
      <Stats jobId={jobId} />
      <JobStatus jobId={jobId} />
    </div>
  );
}

export default JobStatusScreen;
