<script lang="ts">
  import Center from "../utils/Center.svelte";
  import Input from "../utils/Input.svelte";
  import Button from "../utils/Button.svelte";
  import { pb } from "../../pocketbase.svelte";
    import { ClientResponseError } from "pocketbase";
    import Auth from "./Auth.svelte";

  // svelte-ignore non_reactive_update
  let username = "";
  // svelte-ignore non_reactive_update
  let password = "";
  // svelte-ignore non_reactive_update
  let passwordConfirm = "";

  let authError = $state("")

  let { cancel }: { cancel: () => void } = $props();

  async function register() {
    if (password.length < 8 || password !== passwordConfirm) return;

    const data = {
      username,
      password,
      passwordConfirm,
    };

    try {
      const record = await pb.collection("users").create(data);

      const authData = await pb
        .collection("users")
        .authWithPassword(username, password);

      console.log(record, authData)
    } catch (error) {
      if(error instanceof ClientResponseError) {
        console.dir(error)
        authError = error.response.message
      }
    }
  }
</script>

<Center>
  <form action="javascript:void(0);" class="select-none flex flex-col items-start gap-2">
    <Input name="username" labelSize="larger" inputWidth="16rem" bind:value={username}
      >Username:</Input>
    <Input
      name="password"
      type="password"
      labelSize="larger"
      inputWidth="16rem"
      bind:value={password}>Password:</Input>
    <Input
      name="password"
      type="password"
      labelSize="larger"
      inputWidth="16rem"
      bind:value={passwordConfirm}>Confirm password:</Input>
    <Button type="submit" width="16rem" onclick={register}>Register</Button>
    <Button type="submit" width="16rem" onclick={cancel}>Cancel</Button>
    <p class="text-center text-red-500 w-[100%]">{authError === "" ? "" : authError}</p>
  </form>
</Center>
