<script lang="ts">
  import { goto } from '$app/navigation';
  import { login } from '$lib/auth/session';

  let email: string = "";
  let password: string = "";

  let formError = false;
  let errorMessage: string | null = null;

  function isValidEmail(email: string | null) {
    const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return typeof email === 'string' ? emailRegex.test(email) : false;
  }

  function isValidpassword(password: string | null) {
    return typeof password === 'string' ? password.length > 0 : false;
  }

  async function handleFormSubmit(event: SubmitEvent) {
    event.preventDefault();

    if (!isValidEmail(email)) {
      console.log("Invalid email address format.");
      return;
    }
    if (!isValidpassword(password)) {
      console.log("Invalid password format.");
      return;
    }

    try {
      await login(email, password);
      goto('/');
    } catch (error: any) {
      errorMessage = error.message;
      formError = true;
    }
  }
</script>

<div class="flex flex-col items-center gap-y-4">
  <h1>Log In</h1>
  <form action="" method="post" on:submit={handleFormSubmit}>
    <fieldset class="flex flex-col gap-y-4 max-w-lg">
      <legend>Please enter your login credentials</legend>
      <div class="flex flex-col">
        <input bind:value={email} type="email" name="email" placeholder="user@example.com" required class="block" />
        <label for="email" class="block">Email</label>
      </div>
      <div class="flex flex-col">
        <input bind:value={password} type="password" name="password" required class="block" />
        <label for="password" class="block">Password</label>
      </div>
      <button type="submit" name="submit">Log In</button>
      {#if formError}
        <p class="text-red-500">{errorMessage}</p>
      {/if}
    </fieldset>
  </form>
</div>
