<script>
    import Button from "$lib/components/base/Button.svelte";
    import Input from "$lib/components/base/Input.svelte";
    import { onMount } from "svelte";

    let brawlsets = $state([])
    let deckImporter = $state("")
    let selectedBset = $state("0")
    let deckName = $state("")
    let deckUrl = $state("")
    let commander = $state("")
    let token = $state("")

    let decks = $state("")

    let error = $state("")
    let valid = $state("")

    onMount( async () => {
        const storageData = window.localStorage.getItem("pocketbase_auth")
        if (storageData != null) {
          const jsonData = JSON.parse(storageData)
          token = jsonData.token
        }

        fetch("/json/misc/brawlsets")
            .then( response => response.json() )
            .then( data => {
                let sortedData = data
                sortedData.sort((a,b) => a.Name.localeCompare(b.Name))
                brawlsets = sortedData
            })

        fetch("/api/deck", {
          headers: {Authorization: token, "Content-Type": "application/json"},
        }).then((res) => {
          if(res.status == 200) {
            res.json().then((apiData) => {
              decks = apiData
              console.log(apiData)
            })
          } else if (res.status == 401 || res.status == 400) {
            res.json().then((apiData) => {
              console.log(apiData)
            })
          }
        })
        
    })

    function setCommander(txt) {
      let lines = txt.split("\n")
      commander = lines[lines.length - 1].slice(1)
    }
    
    function getDataFromLine(line){
      if(line != "") {
        const data = line.split(" ")
        const amount = parseInt(data[0])
        const name = data.slice(1).join(" ").split(" // ")[0].split("/")[0]
        return {"name":name, "amount":amount}
      } else {
        return null
      }
    }

    function importDeck(){
      error = ""
      valid = ""
      const deckText = deckImporter
      let lines = deckText.split("\n")
      lines = lines.filter((line) => line.match(/[0-9]+\s[\w]+/) != undefined)
      const dataToSend = { name: deckName, url: deckUrl, selected_bset:  selectedBset,commander_name: getDataFromLine(commander).name, cards: [] }
      lines.slice(0, lines.length - 1).forEach((line) => {
        const data = getDataFromLine(line)
        if(data != null) {
          dataToSend.cards.push(data)
        }
      });

      console.log(dataToSend)

      fetch('/api/deck/create', {
        method: "POST",
        headers: {Authorization: token, "Content-Type": "application/json"},
        body: JSON.stringify(dataToSend)
      }).then((res) => {
        if(res.status == 200) {
          res.json().then((apiData) => {
            deckImporter = ""
            selectedBset = ""
            deckName = ""
            deckUrl = ""
            commander = ""
            console.log(apiData)
            valid = apiData["message"]
          })
        } else if (res.status == 401 || res.status == 400) {
          res.json().then((apiData) => {
            console.log(apiData)
            error = apiData["message"]
          })
        }
      })
    }

</script>

<div class="flex flex-col w-full items-center p-4 gap-4">
  <div class="flex flex-col-reverse md:flex-row max-w-6xl w-full gap-4">
    <div class="flex flex-col w-full gap-2">
      <textarea placeholder="Deck list dans le format MTGO" class="h-60 p-2 border-black border-1" bind:value={deckImporter} oninput={(e) => setCommander(e.target.value)}></textarea>
      <span>Commandant : {commander}</span>
    </div>
    <div class="flex flex-col w-full gap-4">
      <Input type="text" placeholder="Nom du deck" bind:value={deckName} />
      <Input type="text" placeholder="Url du deck (facultatif)" bind:value={deckUrl} />
      <select bind:value={selectedBset}>
        <option value="0">Selectionnez un Brawlset...</option>
        {#each brawlsets as brawlset}
          <option value={brawlset.SanitizedName}>
            {brawlset.Name}
          </option>
        {/each}
      </select>
      <Button onclick={importDeck}>Importer</Button>
      {#if error != ""}
        <span class="bg-red-200 text-sm rounded-md p-2">{error}</span>
      {/if}
      {#if valid != ""}
        <span class="bg-green-200 text-sm rounded-md p-2">{valid}</span>
      {/if}
    </div>
  </div>
  <h2 class="font-beleren text-2xl w-full max-w-6xl">Liste de decks</h2>
  <div class="w-full max-w-6xl grid grid-cols-2">
    {#each decks as deck}
    <details>
      <summary class="flex-row flex">
        <h3 class="text-xl">{deck.name}</h3>
      </summary>
      <div class="mt-4">
        <span>{deck.commander.name}</span>
        <ul class="grid grid-cols-2">
            {#each deck.cartes as carteData}
              <li>{carteData.amount}x {carteData.carte.name}</li>
            {/each}
        </ul>
      </div>
    </details>
    {/each}
  </div>
</div>
