<script lang="ts">
  import type { PageData } from "./$types";
  import { onMount } from "svelte";
  import { 
    APIKundeAnmelden,
    APICreateOrder 
  } from "$lib/api_caller";
  import {
    istAuthentiziertKunde,
    spezifischeDatenKunde,
  } from "$lib/user_state";
  import { browser } from "$app/environment";
  import { Buffer } from "buffer";
    import { goto } from "$app/navigation";
  export let data: PageData;

  let kundendaten: any;
  let username:any
  onMount(() => {
    (async () => {
      if (istAuthentiziertKunde()) {
        kundendaten = await APIKundeAnmelden(
          spezifischeDatenKunde().username,
          spezifischeDatenKunde().passwort,
        );
        username = kundendaten[0].KundenUsername
        console.log("username: " + username)
        
      }
    })();
  });
  let token: string = browser
    ? window.sessionStorage.getItem("ItemMap") ?? ""
    : "";
  let items: any = JSON.parse(data.items);
  let itemsAndCount: Array<string>;
  let selectedItemIDs: Array<string>;
  let selectedItemIDsInt: Array<number>;
  let selectedItemCounts: Array<string>;
  let selectedItemCountsInt: Array<number>;
  let selectedItems: any;
  let summe: number;
  let anmerkung: string;
  

  let restaurantUsername: string = data.resUsername
  if (token) {
    itemsAndCount = JSON.parse(token);

    selectedItemIDs = itemsAndCount.map(([itemID]) => itemID);
    itemsAndCount.sort((a, b) => Number(a[0]) - Number(b[0]));
    selectedItemCounts = itemsAndCount.map(([_, count]) => count);

    selectedItems = items.filter((item) =>
    selectedItemIDs.includes(item.ItemID),
    );
    selectedItemIDsInt = selectedItemIDs.map(Number);
    selectedItemCountsInt = selectedItemCounts.map(Number)
  }

  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = (currentDate.getMonth() + 1).toString().padStart(2, "0");
  const currentDay = currentDate.getDate().toString().padStart(2, "0");
  const currentHour = currentDate.getHours().toString().padStart(2, "0");
  const currentMinute = currentDate.getMinutes().toString().padStart(2, "0");
  const currentSecond = currentDate.getSeconds().toString().padStart(2, "0");

  const eingangszeit = ` ${currentHour}:${currentMinute}:${currentSecond}`;
  const eingangstag = currentYear + "-" + currentMonth + "-" + currentDay;

  function submitOrder(){
    APICreateOrder(username,anmerkung,selectedItemIDsInt,eingangszeit,eingangstag,restaurantUsername,selectedItemCountsInt)
  }

  function decrementCounter(index: number) {
    if (selectedItemCountsInt[index] > 0) {
      selectedItemCountsInt[index] -= 1;
      updateTotalSum();
    }
  }
  function incrementCounter(index: number) {
     
    selectedItemCountsInt[index] += 1;
    updateTotalSum();
  }
  function updateTotalSum() {
    summe = selectedItemCountsInt.reduce((sum, count, index) => {
      return sum + count * items[index].Preis;
    }, 0);
  }
  updateTotalSum();
  console.log(selectedItems);
  
</script>

<main>
{#if istAuthentiziertKunde()}
  <div class="shopping-cart scale-150" style="margin-top:10%; height: 10%;">
    <!-- Title -->
    <div class="title">Warenkorb</div>

    {#if selectedItems?.length > 0}
      {#each selectedItems as item, index (item)}
        <!-- Product #1 -->
        <div class="item">
          <div class="buttons">
            <button class="delete-btn" on:click={remove item}></button>
          </div>
          <div class="avatar">
            {#if item.Bild}
            <div class="scale-150">
              <img src={URL.createObjectURL(
                new Blob([Buffer.from(item.Bild.data, "base64")]),
              )}
              alt="" 
              />
            </div>
            {/if}
          </div>
        

          <div class="description">
            <span>{item.Name}</span>
            <span>Beschreibung1</span>
          </div>

          <div class="quantity">
            <button
              class="plus-btn"
              type="button"
              name="button"
              on:click={() => incrementCounter(index)}
            >
              <img src="/plus.svg" alt="" />
            </button>
            <input type="text" name="name" bind:value={selectedItemCountsInt[index]} />
            <button
              class="minus-btn"
              type="button"
              name="button"
              on:click={() => decrementCounter(index)}
            >
              <img src="/minus.svg" alt="" />
            </button>
          </div>

          <div class="total-price">{item.Preis + "€"}</div>
        </div>
      {/each}
      <div style="display: flex; justify-content: flex-end;"> Gesamt: {summe}€</div>
      <div>
        <textarea class="textarea" placeholder="Anmerkungen hinzufügen" style="margin-left: 4%;" bind:value={anmerkung}></textarea>
      </div>
    {:else}
      <span>Ihr Warenkorb ist leer</span>
    {/if}
    <div style="display: flex; justify-content: flex-end;">
      <button class="btn btn-primary" type="button" 
      on:click={()=> {submitOrder();
      goto("/bestellhistorie");}}>Bestellen</button>
    </div>
  </div>
{:else}
  <p>DU BIST NICHT ANGEMELDET</p>
{/if}
</main>

please immplement a delete item function for the delete button