import { useEffect, useState } from "@theia/core/shared/react";
import * as React from "react";
import { createUseStyles } from "react-jss";
import {
  LocalStorageKey,
  RCloneActions,
  RCloneEndPoints,
} from "../../constants";
import fetchRClone from "../../helpers/fetchRClone";
import useInterval from "../../hooks/useInterval";
import StatRow from "../Stats/components/StatRow";
import { useStorjWidgetContext } from "../StorjWidget/StorjWidget.context";
import { IJobStatus, IStoredJob } from "../StorjWidget/StorjWidget.interface";

const useStyles = createUseStyles({
  statsContainer: {
    display: "flex",
    flexDirection: "column",
  },
});
type Props = {
  jobId?: number;
};
function JobStatus(props: Props) {
  const { jobId } = props;
  const { selectedAction } = useStorjWidgetContext();
  const classes = useStyles();
  const [status, setStatus] = useState<IJobStatus>({} as IJobStatus);
  const [isJobValid, setIsJobValid] = useState(true);
  const localStorageKey =
    selectedAction === RCloneActions.SYNC
      ? LocalStorageKey.JOBS_SYNC
      : LocalStorageKey.JOBS_COPY;
  useEffect(() => {
    getJobStatus();
    if (jobId) {
      setIsJobValid(true);
    }
  }, [jobId]);

  useEffect(() => {
    if (!isJobValid) {
      deleteExpiredJobFromStorage();
    }
  }, [isJobValid]);

  useInterval(() => {
    getJobStatus();
  }, 2000);

  const deleteExpiredJobFromStorage = () => {
    const storedJobs = localStorage.getItem(localStorageKey);
    if (storedJobs) {
      let jobList = JSON.parse(storedJobs);
      let index = jobList.findIndex((i: IStoredJob) => i.jobId === jobId);
      jobList.splice(index, 1);
      localStorage.setItem(localStorageKey, JSON.stringify(jobList));
    }
  };

  const getJobStatus = async () => {
    if (!((jobId || jobId === 0) && isJobValid)) {
      return;
    }
    const options = {
      body: JSON.stringify({
        jobid: jobId,
      }),
    };
    try {
      const res = await fetchRClone(RCloneEndPoints.getStatusForJob, options);
      const json = await res.json();
      if (json.status === 500) {
        setIsJobValid(false);
      } else {
        setIsJobValid(true);
      }
      setStatus(json);
      console.log("response: ", json);
    } catch (error) {
      console.error(error);
    } finally {
    }
  };
  if (!jobId) {
    return null;
  }
  return (
    <div>
      <h3>Job Status</h3>
      <div className={classes.statsContainer}>
        {!isJobValid ? (
          <p>
            This job is finished, and it will be removed from the job list. So
            please take a record of the job stats, if you want.
          </p>
        ) : (
          <>
            <StatRow label="Finished" value={status.finished} />
            <StatRow label="Success" value={status.success} />
            <StatRow label="Start Time" value={status.startTime} />
            <StatRow label="End Time" value={status.endTime} />
            <StatRow label="Duration" value={status.duration} unit="s" />
            <StatRow label="Error" value={status.error} />
          </>
        )}
      </div>
    </div>
  );
}

export default JobStatus;
