import { useCallback } from "react";
import { useMutation } from "urql";
import * as inputs from "../components/inputs";
import { useNavigate } from "react-router-dom";
import { SubmitButtonElement } from "../components/_layouts/_organisms/_molecules/_atoms/SubmitButtonElement";
import {
  CreateCompanyInput,
  CreateCompanyResponse,
} from "../gql-codegen/graphql";
import { CreateCompanyMutation } from "../gql-operations/company/CreateCompanyMutation";

export function CreateCompany() {
  const navigate = useNavigate();

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

  const onSubmit = useCallback(
    (e: React.FormEvent | undefined) => {
      e?.preventDefault();

      // @ts-ignore
      const name = e.target.elements.name.value.trim();

      executeMutation({
        input: { name },
      });
    },
    [executeMutation],
  );

  if (error) {
    navigate("/dashboard");
  }

  if (data) {
    // @ts-ignore
    navigate(`/company/${data?.createCompany?.company?.id}`);
  }

  return (
    <>
      <div className="border-b border-gql-vis-grey-2 p-5">
        <h2 className="text-2xl">Create Company</h2>
      </div>

      <form id="create-company" onSubmit={onSubmit} className="space-y-6 p-5">
        <div className="w-1/5">
          <inputs.Label htmlFor={"name"} content={"Company name"} />
          <div className="my-5">
            <inputs.Text name={"name"} disabled={fetching} required={true} />
          </div>
        </div>

        <div className="w-1/5">
          <SubmitButtonElement
            name={"create-company-button"}
            content={"Create Company"}
            disabled={fetching}
          />
        </div>
      </form>
    </>
  );
}
