import React from "react";
import * as Yup from "yup";
import { useFormik } from "formik";
import { Form } from "../../Form";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
import { TextInputElement } from "./_molecules/_atoms/TextInputElement";
import { SubmitButtonElement } from "./_molecules/_atoms/SubmitButtonElement";
import { useMutation } from "urql";
import {
  CreateCompanyInput,
  CreateCompanyResponse,
} from "../../../gql-codegen/graphql";
import { CreateCompanyMutation } from "../../../gql-operations/company/CreateCompanyMutation";
import {
  CREATE_COMPANY_BUTTON,
  CREATE_COMPANY_COMPONENT,
  CREATE_COMPANY_NAME,
} from "../../../testing";

export default function CreateCompanyOnboarding() {
  const navigate = useNavigate();

  const [, executeMutation] = useMutation<
    CreateCompanyResponse,
    { input: CreateCompanyInput }
  >(CreateCompanyMutation);

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

        if (result.error) {
          if (
            result.error.message.includes("Cannot have more than one Company")
          ) {
            toast.error(
              "Currently, we only support 1 company per user. More companies coming soon... Redirecting to dashboard. ",
              {
                position: toast.POSITION.BOTTOM_RIGHT,
              },
            );

            navigate("/login");
          } else {
            toast.error("Something went wrong, please try again...", {
              position: toast.POSITION.BOTTOM_RIGHT,
            });
          }
        }

        if (data) {
          if (!data.success) {
            // @ts-ignore
            if (data.message.includes("Cannot have more than one Company")) {
              toast.error(
                "Currently, we only support 1 company per user. More companies coming soon... Redirecting to dashboard. ",
                {
                  position: toast.POSITION.BOTTOM_RIGHT,
                },
              );

              navigate("/dashboard");
            } else {
              toast.error("Something went wrong, please try again...", {
                position: toast.POSITION.BOTTOM_RIGHT,
              });
            }
          } else {
            toast.success("Company created! Please login again...", {
              position: toast.POSITION.BOTTOM_RIGHT,
            });

            navigate("/login");
          }
        }
      });
    },
  });

  return (
    <div className="flex justify-center h-full">
      <div className="z-10 flex flex-1 flex-col h-full">
        <div className=" mx-auto w-full h-full">
          <div className="flex flex-col justify-center h-full">
            <div className="mx-auto w-full max-w-sm lg:w-96">
              <div>
                <div>
                  <h2 className="m-6 text-gray-900 text-md font-medium tracking-tight leading-tight text-center">
                    In order to start using the application you need to create a
                    Company first. Don&apos;t worry, you can change these
                    details later.
                  </h2>
                </div>
              </div>
              <Form
                id={CREATE_COMPANY_COMPONENT}
                onSubmit={(e: React.FormEvent) => {
                  e.preventDefault();
                  validation.handleSubmit();
                  return false;
                }}
              >
                <TextInputElement
                  id={CREATE_COMPANY_NAME}
                  name="name"
                  label="Company Name"
                  disabled={false}
                  required
                  error={validation.errors.name ? true : false}
                  onChange={validation.handleChange}
                  onBlur={validation.handleBlur}
                  helperText={validation.errors.name}
                />
                <SubmitButtonElement
                  id={CREATE_COMPANY_BUTTON}
                  content={"Create Company"}
                  disabled={
                    (!validation.touched.name ||
                      // @ts-ignore
                      validation.errors.name?.length > 0) ??
                    false
                  }
                  type="submit"
                />
              </Form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
