import { useMutation } from "urql";
import * as Yup from "yup";
import { useNavigate, useParams } from "react-router-dom";
import { useFormik } from "formik";
import { SubmitButtonElement } from "./_organisms/_molecules/_atoms/SubmitButtonElement";
import { Form } from "../Form";
import { toast } from "react-toastify";
import { TextInputElement } from "./_organisms/_molecules/_atoms/TextInputElement";
import {
  CreateProjectInput,
  CreateProjectMutationDocument,
  CreateProjectResponse,
} from "../../gql-codegen/graphql";
import {
  ButtonType,
  DefaultButton,
} from "./_organisms/_molecules/_atoms/DefaultButtonElement";
import {
  CREATE_PROJECT_BUTTON_FORM,
  CREATE_PROJECT_COMPONENT,
  CREATE_PROJECT_NAME,
} from "../../testing";

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

  const [, executeMutation] = useMutation<
    CreateProjectResponse,
    { input: CreateProjectInput }
  >(CreateProjectMutationDocument);

  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 Project.")
        .min(4, "Project name too short.")
        .max(64, "Project name cannot be longer than 64 characters."),
    }),
    onSubmit: ({ name }) => {
      executeMutation({
        input: {
          name: name,
        },
      })
        .then((result) => {
          // @ts-ignore
          const data: CreateProjectResponse = result.data.createProject;

          if (result.error) {
            if (
              result.error.message.includes(
                "Project with that name already exists",
              )
            ) {
              toast.error(
                "Project with that name already exists, please try again with a different name.",
                {
                  position: toast.POSITION.BOTTOM_RIGHT,
                },
              );
            } else {
              toast.error("Something went wrong, please try again...", {
                position: toast.POSITION.BOTTOM_RIGHT,
              });
            }
          }

          if (data) {
            if (!data.success) {
              if (
                data.message &&
                data.message.includes("Project with that name already exists")
              ) {
                toast.error(
                  "Project with that name already exists, please try again with a different name.",
                  {
                    position: toast.POSITION.BOTTOM_RIGHT,
                  },
                );
              } else {
                toast.error("Something went wrong, please try again...", {
                  position: toast.POSITION.BOTTOM_RIGHT,
                });
              }
            } else {
              toast.success(
                "Project successfully created! Redirecting to Projects overview.",
                {
                  position: toast.POSITION.BOTTOM_RIGHT,
                },
              );

              navigate(
                `/company/${params.companyId}/project/${data.project?.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 a Project
        </h3>

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

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