<script lang="ts">
  import { onMount } from "svelte";
  import { goto, invalidate } from "$app/navigation";
  import { scale } from 'svelte/transition';
  import { addToast } from '$lib/ToastSystem/Toaster.svelte';
  import BatteryIcon from "$lib/icons/BatteryIcon.svelte";
  import BSlideOverlay from "$lib/BSlideOverlay.svelte";

  let { data } = $props();

  onMount(() => {
    const interval = setInterval(() => {
      invalidate('app:chargecontroller');
    }, 5000);
    return () => {
      clearInterval(interval);
    };
  });

  const energykWh: string = $derived.by(() => {
    const wh = data.chargecontroller.active_charge?.energy_wh ?? 0;
    return (wh / 1000).toFixed(2);
  });
  const powerkWh: string = $derived.by(() => {
    const wh = data.chargecontroller.active_charge?.last_power?.power ?? 0;
    return (wh / 1000).toFixed(2);
  });

  let showOverlay = $state(false);
  let stoppingCharge = $state(false);

  async function stopCharge() {
    if (stoppingCharge) return;
    stoppingCharge = true;
    try {
      const response = await fetch(`/api/public/1/chargecontroller/${data.qrcode}/stop_charge/`, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
        }
      });
      if (response.ok) {
        addToast({
          closeDelay: 5000,
          data: {
            title: 'Charge Stopped',
            description: '',
            type: 'success',
          }
        });
        await invalidate('app:chargecontroller');
        await goto(`/${data.qrcode}`);
      } else {
        addToast({
          closeDelay: 5000,
          data: {
            title: 'Error',
            description: response.statusText ?? 'unknown',
            type: 'error',
          }
        });
      }
    } finally {
      stoppingCharge = false;
    }
  }
</script>

<div class="visible bg-green-700/80 h-full w-full flex flex-col justify-center items-center gap-12">
  <div>
    <BatteryIcon/>
  </div>
  <div class="text-center">
    <p>Energia erogata a {data.user.username}:</p>
    <p class="text-4xl"><span class="text-5xl">{energykWh}</span> kWh</p>
    <p class="text-sm">Potenza misurata: {powerkWh} kW</p>
  </div>
  <div class="w-[90%]">
    <button class="btn btn-warning btn-xl w-full" onclick={() => showOverlay = true}>Interrompere la ricarica</button>
  </div>
  <div class="text-center w-[70%] flex flex-col gap-5 text-sm">
    <p>
      «Ciò che sta accadendo ci pone di fronte all’urgenza di procedere in una coraggiosa rivoluzione culturale.»
    </p>
    <p>
      Papa Francesco, Enciclica Laudato Si’
    </p>
  </div>
  <BSlideOverlay bind:show={showOverlay} closable={!stoppingCharge}>
    {#snippet children({ closeOverlay })}
      <p class="font-bold w-[90%] text-wrap uppercase text-center">Sei sicuro di voler interrompere la ricarica?</p>
      <div class="flex flex-row justify-around gap-4 w-full">
        <button class="btn btn-primary btn-xl w-24 grid" onclick={stopCharge}>
          {#if stoppingCharge}
            <span transition:scale class="col-start-1 col-end-2 row-start-1 row-end-2 loading"></span>
          {:else}
            <span transition:scale class="col-start-1 col-end-2 row-start-1 row-end-2">SI</span>
          {/if}
        </button>
        <button class="btn btn-secondary btn-xl w-24" onclick={closeOverlay}>NO</button>
      </div>
    {/snippet}
  </BSlideOverlay>
</div>
