import { useCallback } from "react";
import gql from "gql-tag";
import { useMutation } from "urql";
import * as inputs from "../components/inputs";
import { useNavigate, useParams } from "react-router-dom";
import { SubmitButtonElement } from "../components/_layouts/_organisms/_molecules/_atoms/SubmitButtonElement";

const addCompanyMemberMutation = gql`
  mutation AddCompanyMemberMutation($companyId: String!, $userEmail: String!) {
    addCompanyMember(input: { companyId: $companyId, userEmail: $userEmail }) {
      success
      message
    }
  }
`;

export function AddCompanyMember() {
  const navigate = useNavigate();
  const params = useParams<{ companyId: string }>();

  const [{ data, error }, executeMutation] = useMutation(
    addCompanyMemberMutation,
  );

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

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

      executeMutation({
        userEmail,
        companyId: params.companyId,
      });
    },
    [params.companyId, executeMutation],
  );

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

  if (data) {
    navigate(`/company/${params.companyId}`);
  }

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

      <form id="create-project" onSubmit={onSubmit} className="space-y-6 p-5">
        <div className="w-1/5">
          <inputs.Label htmlFor={"email"} content={"User Email"} />
          <inputs.Email name={"email"} disabled={false} required={true} />
        </div>

        <div className="w-1/5">
          <SubmitButtonElement
            name={"add-company-member-button"}
            content={"Create"}
            disabled={false}
          />
        </div>
      </form>
    </div>
  );
}
