<script lang="ts">
  import { Button, Heading, P, Range } from "flowbite-svelte";
  import { GetGame, SaveStep, UndoFor } from "../../wailsjs/go/main/App";
  import { model } from "../../wailsjs/go/models";
  import { derived } from "svelte/store";
  import TichuSelect from "@/components/TichuSelect.svelte";
  import { FloppyDiskSolid, UndoOutline } from "flowbite-svelte-icons";

  let { gameId }: { gameId: number } = $props();

  let game: model.Game = $state(new model.Game());
  let rawPoints: number = $state(50);
  let pointsTeamA = $derived.by(() => {
    if (rawPoints == -30) {
      return 200;
    }
    if (rawPoints == 130) {
      return 0;
    }
    return 100 - rawPoints;
  });
  let pointsTeamB = $derived.by(() => {
    if (rawPoints == -30) {
      return 0;
    }
    if (rawPoints == 130) {
      return 200;
    }

    return rawPoints;
  });
  function save() {
    let step = new model.Step();
    step.GameID = gameId;
    step.PointsTeamA = pointsTeamA;
    step.AdderTeamA = adderTeamA;
    step.PointsTeamB = pointsTeamB;
    step.AdderTeamB = adderTeamB;

    SaveStep(step).then(() => {
      update();
      rawPoints = 50;
      adderTeamA = 0;
      adderTeamB = 0;
    });
  }

  addEventListener("keydown", (event) => {
    switch (event.key) {
      case "Enter":
        save();
        break;
      case "z":
        if (event.ctrlKey) {
          UndoFor(game).then(update);
        }
        break;
      case "u":
        UndoFor(game).then(update);
        break;
    }
  });

  let adderTeamA = $state(0);
  let adderTeamB = $state(0);

  function update() {
    GetGame(gameId).then((g) => (game = g));
  }
  $effect(update);
</script>

<div
  class="grid grid-cols-2 gap-5 m-5"
  onwheel={(e) => {
    if (e.deltaY > 0 && rawPoints < 130) {
      rawPoints += 5;
    }
    if (e.deltaY < 0 && rawPoints > -30) {
      rawPoints -= 5;
    }
  }}
>
  <Heading class="text-center">{game.TeamA}</Heading>
  <Heading class="text-center">{game.TeamB}</Heading>
  <div class="col-span-2 flex gap-5 items-center">
    <P>{pointsTeamA}</P>
    <Range
      id="range-minmax"
      min="-30"
      max="130"
      step="5"
      bind:value={rawPoints}
    />
    <P>{pointsTeamB}</P>
  </div>
  <TichuSelect bind:value={adderTeamA} />
  <TichuSelect bind:value={adderTeamB} />
  <div class="col-span-2 flex gap-5 items-center justify-center">
    <Button onclick={save}><FloppyDiskSolid /></Button>
    <Button color="red" onclick={() => UndoFor(game).then(update)}
      ><UndoOutline /></Button
    >
  </div>
</div>
