import type { FormEvent, FormEventHandler } from "react";
import { gql, useMutation } from "@apollo/client";
import Cookies from "js-cookie";
import Router from "next/router";

import * as cookieNames from "../lib/cookieNames";

const LOGIN_MUTATION = gql`
  mutation Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      token
    }
  }
`;

function Login(): JSX.Element {
  const [login, { error }] = useMutation(LOGIN_MUTATION);

  const loginUser: FormEventHandler = async (
    event: FormEvent & { target: HTMLFormElement }
  ): Promise<void> => {
    event.preventDefault();

    const input = {
      email: event.target.email.value as string,
      password: event.target.password.value as string,
    };
    const data = (
      await login({
        variables: { email: input.email, password: input.password },
      })
    ).data;

    if (data) {
      Cookies.set(cookieNames.TOKEN, data.login.token, { expires: 1 });
      Router.push("/");
    }
  };

  return (
    <div>
      <h1>Login:</h1>
      <form onSubmit={loginUser}>
        <label htmlFor="email">Email:</label>
        <br />
        <input type="email" id="email" autoComplete="email" required />
        <br />
        <label htmlFor="password">Password:</label>
        <br />
        <input
          type="password"
          id="password"
          autoComplete="current-password"
          required
        />
        <br />
        <button type="submit">Login</button>
      </form>
      {error && <p style={{ color: "red" }}>{error.message}</p>}
    </div>
  );
}

export default Login;
