import { useMutation } from "urql";
import { useNavigate, useParams } from "react-router-dom";
import * as Yup from "yup";
import { SubmitButtonElement } from "./_organisms/_molecules/_atoms/SubmitButtonElement";
import {
  CreateProjectApiKeyInput,
  CreateProjectApiKeyMutationDocument,
  CreateProjectApiKeyResponse,
} from "../../gql-codegen/graphql";
import { useFormik } from "formik";
import { toast } from "react-toastify";
import { TextInputElement } from "./_organisms/_molecules/_atoms/TextInputElement";
import { Form } from "../Form";
import {
  ButtonType,
  DefaultButton,
} from "./_organisms/_molecules/_atoms/DefaultButtonElement";
import {
  CREATE_KEY_BUTTON_FORM,
  CREATE_KEY_COMPONENT,
  CREATE_KEY_NAME,
} from "../../testing";

export function CreateApiKey() {
  const params = useParams();
  const navigate = useNavigate();

  const [, executeMutation] = useMutation<
    CreateProjectApiKeyResponse,
    { input: CreateProjectApiKeyInput }
  >(CreateProjectApiKeyMutationDocument);

  const validation = useFormik({
    enableReinitialize: true,
    initialValues: {
      name: "",
    },
    validationSchema: Yup.object().shape({
      name: Yup.string()
        .matches(
          new RegExp(/^[\w\-.\s]+$/),
          "Only alphanumeric characters and spaces are allowed.",
        )
        .required("You must enter a name for the API Key.")
        .min(4, "Name too short.")
        .max(64, "Name cannot be longer than 64 characters."),
    }),
    onSubmit: ({ name }) => {
      executeMutation({
        input: {
          name: name,
          projectId: params.projectId as string,
        },
      })
        .then((result) => {
          // @ts-ignore
          const data: CreateProjectApiKeyResponse =
            // @ts-ignore
            result.data.createProjectApiKey;

          if (result.error) {
            throw new Error(result.error.message);
          }

          if (data) {
            if (!data.success) {
              toast.error("Something went wrong, please try again...", {
                position: toast.POSITION.BOTTOM_RIGHT,
              });
            } else {
              toast.success(
                "API Key successfully created! Redirecting to API Keys overview.",
                {
                  position: toast.POSITION.BOTTOM_RIGHT,
                },
              );

              navigate(
                `/company/${params.companyId}/project/${params.projectId}/api-key/${data.projectApiKey?.id}`,
              );
            }
          }
        })
        .catch((result) => {
          console.error(result);
        });
    },
  });

  return (
    <div className="flex flex-col w-full h-full align-top content-start gap-5">
      <div className="flex flex-row w-full space-between">
        <h3 className="text-4xl font-bold text-gql-vis-darkblue">
          Create an API Key
        </h3>

        <div className="ml-auto">
          <DefaultButton
            text="Cancel"
            route="/api-keys"
            type={ButtonType.DANGER}
          />
        </div>
      </div>

      <Form
        id={CREATE_KEY_COMPONENT}
        onSubmit={(e: React.FormEvent) => {
          e.preventDefault();
          validation.handleSubmit();
          return false;
        }}
      >
        <TextInputElement
          id={CREATE_KEY_NAME}
          name="name"
          label="API Key Name"
          disabled={false}
          required
          error={validation.errors.name ? true : false}
          onChange={validation.handleChange}
          onBlur={validation.handleBlur}
          helperText={validation.errors.name}
          value={validation.values.name}
        />
        <SubmitButtonElement
          id={CREATE_KEY_BUTTON_FORM}
          content={"Create Key"}
          disabled={
            (validation.errors.name != undefined &&
              validation.errors.name?.length > 0) ??
            false
          }
          type="submit"
        />
      </Form>
    </div>
  );
}
