import * as React from "react";
import { useEffect, useState } from "@theia/core/shared/react";
import * as Yup from "yup";
import { ErrorMessage, Form, Formik, FormikHelpers } from "formik";
import { useCommonStyles } from "../../StorjWidget.style";
import {
  EScreenView,
  LocalStorageKey,
  RCloneActions,
  RCloneEndPoints,
} from "../../../../constants";
import fetchRClone from "../../../../helpers/fetchRClone";
import { IRCloneFile } from "../../StorjWidget.interface";
import ActionButton from "./components";
import { useStorjWidgetContext } from "../../StorjWidget.context";
import { createUseStyles } from "react-jss";

const ActionsValidationSchema = Yup.object().shape({
  bucket: Yup.string().required("Please select a bucket to proceed."),
});

const useStyles = createUseStyles({
  remoteListText: {
    cursor: "pointer",
    "&:hover": {
      textDecoration: "underline",
    },
    marginLeft: "auto",
  },
  headerContainer: {
    display: "flex",
  },
});

interface FormValues {
  bucket: string;
}
const initialValues: FormValues = {
  bucket: "",
};

type Props = {
  onShowAlert: (message: string) => void;
};
const ActionsScreen = (props: Props) => {
  const { onShowAlert } = props;
  const selectedRemoteName = localStorage.getItem(
    LocalStorageKey.SELECTED_REMOTE
  );
  const { setCurrentScreen, setSelectedAction } = useStorjWidgetContext();
  const [fileListLoading, setFileListLoading] = useState<boolean>(false);
  const [fileList, setFileList] = useState<IRCloneFile[]>([]);
  const commonClasses = useCommonStyles();
  const classes = useStyles();
  useEffect(() => {
    if (!selectedRemoteName) {
      setCurrentScreen(EScreenView.ACCESS_GRANT_SCREEN);
      onShowAlert("You need to set a remote first.");
    }
    getFileList();
  }, []);

  const getFileList = async () => {
    setFileListLoading(true);
    try {
      const options: RequestInit = {
        body: JSON.stringify({ fs: `${selectedRemoteName}:`, remote: "" }),
      };
      const res = await fetchRClone(RCloneEndPoints.getFilesList, options);
      const json = await res.json();
      setFileList(json.list);
    } catch (error) {
      console.error(error);
    } finally {
      setFileListLoading(false);
    }
  };

  const handleSubmit = async (
    values: FormValues,
    helpers: FormikHelpers<FormValues>
  ) => {
    console.log(JSON.stringify(values));
    localStorage.setItem(LocalStorageKey.SELECTED_BUCKET, values.bucket);
  };

  const handleClickAction = async (
    action: RCloneActions,
    values: FormValues
  ) => {
    if (!values.bucket) {
      return;
    }
    switch (action) {
      case RCloneActions.SYNC:
        setCurrentScreen(EScreenView.ACTIONS_SYNC_SCREEN);
        setSelectedAction(RCloneActions.SYNC);
        break;
      case RCloneActions.COPY:
        setCurrentScreen(EScreenView.ACTIONS_COPY_SCREEN);
        setSelectedAction(RCloneActions.COPY);
        break;
    }
  };

  const handleClickRemoteList = () => {
    setCurrentScreen(EScreenView.REMOTE_LIST_SCREEN);
  };

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={ActionsValidationSchema}
    >
      {({ isSubmitting, values, handleChange, handleBlur, submitForm }) => (
        <Form className={commonClasses.form}>
          <div className={classes.headerContainer}>
            <h3>{selectedRemoteName}</h3>
            <h4
              onClick={handleClickRemoteList}
              className={classes.remoteListText}
            >
              My Remote List
            </h4>
          </div>
          <label htmlFor="bucket">Bucket List</label>
          <select
            name="bucket"
            value={values.bucket}
            disabled={fileListLoading}
            onBlur={handleBlur}
            onChange={handleChange}
            className={`theia-input ${commonClasses.selectInput}`}
          >
            <option key="default" value="" label="Select a bucket"></option>
            {fileList?.map((file: IRCloneFile, index: number) => (
              <option
                key={`${file.Name}-${index}`}
                value={file.Name}
                label={file.Name}
              />
            ))}
          </select>
          <ErrorMessage
            className={commonClasses.errorMessage}
            name="bucket"
            component="div"
          />
          <ActionButton
            label="SYNC"
            buttonName="sync"
            key="sync"
            tooltip="Make source and<br />destination identical,<br />modifying destination only."
            onClick={() => {
              submitForm();
              handleClickAction(RCloneActions.SYNC, values);
            }}
            isLoading={isSubmitting}
          />
          <ActionButton
            label="COPY"
            buttonName="copy"
            key="copy"
            tooltip="Copy files from<br />source to destination,<br />skipping already copied."
            onClick={() => {
              submitForm();
              handleClickAction(RCloneActions.COPY, values);
            }}
            isLoading={isSubmitting}
          />
        </Form>
      )}
    </Formik>
  );
};

export default ActionsScreen;
