import * as React from "react";
import * as Yup from "yup";
import { ErrorMessage, Form, Formik, FormikHelpers } from "formik";
import { useStorjWidgetContext } from "../../StorjWidget.context";
import {
  emptyInputErrorMessage,
  EScreenView,
  LocalStorageKey,
  RCloneEndPoints,
  storjGalileoLink,
  storJStorageName,
} from "../../../../constants";
import { useCommonStyles } from "../../StorjWidget.style";
import fetchRClone from "../../../../helpers/fetchRClone";
import { createUseStyles } from "react-jss";
import BackButton from "../../../BackButton";

const AccessGrantValidationSchema = Yup.object().shape({
  accessGrant: Yup.string().required(emptyInputErrorMessage),
  remoteName: Yup.string().required(emptyInputErrorMessage),
});

const useStyles = createUseStyles({
  remoteListText: {
    cursor: "pointer",
    "&:hover": {
      textDecoration: "underline",
    },
    marginLeft: "auto",
  },
  headerContainer: {
    display: "flex",
    alignItems: "center",
  },
  accountText: {
    marginTop: 24,
  },
});
interface FormValues {
  accessGrant: string;
  remoteName: string;
}
const initialValues: FormValues = {
  accessGrant: "",
  remoteName: "",
};

const AccessGrantScreen = () => {
  const selectedRemoteName = localStorage.getItem(
    LocalStorageKey.SELECTED_REMOTE
  );
  const { setCurrentScreen } = useStorjWidgetContext();
  const classes = useStyles();
  const commonClasses = useCommonStyles();

  const handleSubmit = async (
    values: FormValues,
    helpers: FormikHelpers<FormValues>
  ) => {
    const { setSubmitting, setFieldError } = helpers;
    console.log(JSON.stringify(values));
    setSubmitting(true);
    const options = {
      body: JSON.stringify({
        name: values.remoteName,
        type: storJStorageName,
        parameters: { access_grant: values.accessGrant },
      }),
    };
    const aboutOptions = {
      body: JSON.stringify({
        fs: `${values.remoteName}:`,
      }),
    };
    try {
      await fetchRClone(RCloneEndPoints.createConfig, options);
      const response = await fetchRClone(
        RCloneEndPoints.getFsInfo,
        aboutOptions
      );
      if (response.ok) {
        localStorage.setItem(
          LocalStorageKey.SELECTED_REMOTE,
          values.remoteName
        );
        setCurrentScreen(EScreenView.ACTIONS_SCREEN);
      } else {
        await fetchRClone(RCloneEndPoints.deleteConfig, {
          body: JSON.stringify({
            name: values.remoteName,
          }),
        });
        throw new Error();
      }
    } catch (error) {
      setFieldError(
        "accessGrant",
        "Something went wrong while connecting to the Storj. Please make sure that your access grant is valid."
      );
      console.error(error);
    } finally {
      setSubmitting(false);
    }
  };
  const handleClickRemoteList = () => {
    setCurrentScreen(EScreenView.REMOTE_LIST_SCREEN);
  };

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={AccessGrantValidationSchema}
    >
      {({ isSubmitting, values, handleChange }) => (
        <Form className={commonClasses.form}>
          {selectedRemoteName && (
            <div className={classes.headerContainer}>
              <BackButton />
              <h4
                onClick={handleClickRemoteList}
                className={classes.remoteListText}
              >
                My Remote List
              </h4>
            </div>
          )}

          <label htmlFor="remoteName">Remote Name*</label>
          <input
            type="text"
            name="remoteName"
            value={values.remoteName}
            onChange={handleChange}
            placeholder="Give a name for your remote"
            className={`theia-input ${commonClasses.input}`}
          />
          <ErrorMessage
            className={commonClasses.errorMessage}
            name="remoteName"
            component="div"
          />
          <label htmlFor="accessGrant">Access Grant*</label>
          <input
            type="text"
            name="accessGrant"
            value={values.accessGrant}
            onChange={handleChange}
            placeholder="Enter your access grant to access your Storj account"
            className={`theia-input ${commonClasses.input}`}
          />
          <ErrorMessage
            className={commonClasses.errorMessage}
            name="accessGrant"
            component="div"
          />
          <button
            type="submit"
            className={`theia-button primary ${commonClasses.button}`}
            disabled={isSubmitting}
          >
            CREATE REMOTE
            {isSubmitting && (
              <i style={{ marginLeft: 8 }} className="fa fa-spinner fa-spin" />
            )}
          </button>
          {!selectedRemoteName && (
            <i className={classes.accountText}>
              {`Don't have a Storj account yet? You can create a free account from `}
              <a href={storjGalileoLink} target="_blank">
                here
              </a>
              .
            </i>
          )}
        </Form>
      )}
    </Formik>
  );
};

export default AccessGrantScreen;
