<script lang="ts">
  import { user, preferences, token } from "../../stores/auth";
  import { createEventDispatcher, onDestroy, onMount } from "svelte";
  import type { User } from "../../types";
  import { apiURL } from "../../utils";

  export let open: boolean;

  let sizes: Array<any>;
  let selectedSize: number = 1;
  let color: string = "#000000";

  const dispatch = createEventDispatcher();

  const unsubscribe = preferences.subscribe(
    (value: any) => {
      if (value) {
        color = value.color;
        selectedSize = value.size_id;
      }
    },
  );

  function closeDialog() {
    dispatch("close");
  }

  async function updateUserPreferences() {
    const res = await fetch(apiURL("user/preferences"), {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${$token}`,
      },
      body: JSON.stringify($preferences),
    });
  }

  async function getUserPreferences() {
    const res = await fetch(apiURL(`user/${($user as User)!.id}/preferences`),
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${$token}`,
        },
      },
    );
    const updatePreferences = await res.json();
    preferences.set(updatePreferences);
  }

  async function onPreferencesSave(): Promise<void> {
    preferences.update((value) => ({
      ...value!,
      size_id: selectedSize,
      color: color,
    }));

    await updateUserPreferences();
    await getUserPreferences();

    dispatch("close");
  }

  onMount(() => {
    fetch(apiURL("sizes"), {
      method: "GET",
      headers: {
        Authorization: `Bearer ${$token}`,
      },
    })
      .then((res) => res.json())
      .then((val) => (sizes = val));
  });

  onDestroy(() => {
    unsubscribe();
  });
</script>

<dialog {open} on:submit|preventDefault={onPreferencesSave}>
  <h2>User Preferences</h2>
  <form method="dialog">
    <div class="form input group">
      <label for="color">Color</label>
      <input
        id="color"
        name="color"
        type="color"
        bind:value={color}
      />
    </div>
    <div class="form input group">
      <label for="size">Bottle Size</label>
      <select
        bind:value={selectedSize}
      >
        {#if sizes}
          {#each sizes as size}
            <option value={size.id}>{size.size} {size.unit}</option>
          {/each}
        {/if}
      </select>
    </div>
    <button on:click={closeDialog}>Cancel</button>
    <button type="submit">Save</button>
  </form>
</dialog>

<style>
  /* dialog {
    background: white;
    color: black;
  }

  input[type="color"] {
    width: 4em;
    height: 4em;
  } */
</style>
