<script>
  import { createForm } from "svelte-forms-lib";
  import { getNotificationsContext } from "svelte-notifications";
  import { navigate } from "svelte-routing";
  import * as yup from "yup";
  import { authenticationToken } from "../stores.js";
  import api from "../utilities/api";
  import { setToken } from "../utilities/authToken";
  import notificationObject from "../utilities/notification";


  const { addNotification } = getNotificationsContext();

  const { form, errors, state, handleChange, handleSubmit } = createForm({
    initialValues: {
      email: "",
      password: "",
    },

    validationSchema: yup.object().shape({
      email: yup.string().email().required(),
      password: yup.string().required(),
    }),

    onSubmit: (values) => {
      addNotification(
        notificationObject({
          text: "Signing you in ...",
        })
      );

      api()
        .post("/users/sign_in", { user: values })
        .then((response) => {
          authenticationToken.set(response.headers.authorization);
          addNotification(
            notificationObject({
              text: "Successfully logged in",
              type: "success",
            })
          );
          setToken(response.headers.authorization);
          navigate("/", { replace: true });
        })
        .catch((error) => {
          addNotification(
            notificationObject({
              text:
                error.response?.status == 401
                  ? "Invalid credentials"
                  : "An error has happened while trying to sign you in. Please try again later.",
              type: "danger",
            })
          );
        });
    },
  });
</script>

<div class="colums">
  <div class="column is-4 is-offset-one-quarter">
    <h1 class="title">Sign In</h1>
    <p>Please log in to enjoy all the great content</p>
    <br />

    <form on:submit={handleSubmit}>
      <div class="field">
        <label class="label" for="email">E-Mail</label>
        <div class="control has-icons-left has-icons-right ">
          <input
            class="input is-failure"
            id="email"
            name="email"
            type="email"
            on:change={handleChange}
            on:blur={handleChange}
            bind:value={$form.email}
          />
          {#if $errors.email}
            <small class="help is-danger">{$errors.email}</small>
          {/if}
        </div>
      </div>

      <div class="field">
        <label class="label" for="password">Password</label>
        <div class="control has-icons-left has-icons-right ">
          <input
            class="input is-failure"
            id="password"
            name="password"
            type="password"
            on:change={handleChange}
            on:blur={handleChange}
            bind:value={$form.password}
          />
          {#if $errors.password}
            <small class="help is-danger">{$errors.password}</small>
          {/if}
        </div>
      </div>

      <button type="submit" class="button is">Login</button>
    </form>
  </div>
</div>

<br />
<footer class="footer">
  <div class="content has-text-centered">
    <p>
      <strong>MegaMeme</strong> | Copyright &#169; 2021 by L.Ceriani, A.Pfister &#38;
      M.Brändli
    </p>
  </div>
</footer>
