<script>
  import { _ } from "svelte-i18n";
  import store from "../../store";
  import {
    DonationService,
    DonorService,
    RunnerService,
  } from "@odit/lfk-client-js";
  import Toastify from "toastify-js";
  import PromiseError from "../base/PromiseError.svelte";
  import Select from "svelte-select";
  let data_loaded = false;
  export let params;
  $: delete_triggered = false;
  $: original_data = {};
  $: editable = {};
  $: donor = {};
  $: runner = {};
  $: current_donors = [];
  $: current_runners = [];
  $: amount_input = 0;
  $: is_amount_valid = amount_input > 0;
  $: paid_amount_input = 0;
  $: is_paid_amount_valid = paid_amount_input > 0;
  $: is_everything_set =
    editable.donor != null &&
    ((original_data.responseType == "DISTANCEDONATION" &&
      editable?.runner != null) ||
      original_data.responseType !== "DISTANCEDONATION");
  $: changes_performed =
    !(JSON.stringify(original_data) === JSON.stringify(editable)) ||
    (original_data.responseType == "DISTANCEDONATION" &&
      !(Math.floor(amount_input * 100) === original_data.amountPerDistance)) ||
    (original_data.responseType !== "DISTANCEDONATION" &&
      !(Math.floor(amount_input * 100) === original_data.amount)) ||
      !(Math.floor(paid_amount_input * 100) === original_data.paidAmount);
  $: save_enabled = changes_performed && is_amount_valid && is_everything_set;

  const promise = DonationService.donationControllerGetOne(
    params.donationid
  ).then((data) => {
    data_loaded = true;
    original_data = Object.assign({}, data);
    editable = Object.assign({}, original_data);
    paid_amount_input = data.paidAmount / 100;
    if (data.responseType == "DISTANCEDONATION") {
      amount_input = data.amountPerDistance / 100;
      RunnerService.runnerControllerGetAll().then((val) => {
        current_runners = val.map((r) => {
          return { label: getDonorLabel(r), value: r };
        });
        runner = current_runners.find((g) => g.value.id == editable.runner.id);
      });
    } else {
      amount_input = data.amount / 100;
    }
    DonorService.donorControllerGetAll().then((val) => {
      current_donors = val.map((r) => {
        return { label: getDonorLabel(r), value: r };
      });
      donor = current_donors.find((g) => g.value.id == editable.donor.id);
    });
  });
  const getDonorLabel = (option) =>
    option.firstname + " " + (option.middlename || "") + " " + option.lastname;
  const filterDonors = (label, filterText, option) =>
    label.toLowerCase().includes(filterText.toLowerCase()) ||
    option.value.id.toString().startsWith(filterText.toLowerCase());

  function submit() {
    if (data_loaded === true && save_enabled) {
      Toastify({
        text: $_('updating-donation'),
        duration: 2500,
      }).showToast();
      let postdata = {};
      editable.paidAmount = paid_amount_input*100;
      if (original_data.responseType === "DISTANCEDONATION") {
        editable.amountPerDistance = Math.floor(amount_input * 100);
        postdata = Object.assign(postdata, editable);
        postdata.runner = postdata.runner.id;
        postdata.donor = postdata.donor.id;
        DonationService.donationControllerPutDistance(
          original_data.id,
          postdata
        )
          .then((resp) => {
            Object.assign(original_data, editable);
            original_data = original_data;
            Toastify({
              text: $_('donation-updated'),
              duration: 2500,
              backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            }).showToast();
          })
          .catch((err) => {});
      } else {
        editable.amount = Math.floor(amount_input * 100);
        postdata = Object.assign(postdata, editable);
        postdata.donor = postdata.donor.id;
        DonationService.donationControllerPutFixed(original_data.id, postdata)
          .then((resp) => {
            Object.assign(original_data, editable);
            original_data = original_data;
            Toastify({
              text: $_('donation-updated'),
              duration: 2500,
              backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            }).showToast();
          })
          .catch((err) => {});
      }
    } else {
    }
  }
  function deleteDonation() {
    DonationService.donationControllerRemove(original_data.id, false)
      .then((resp) => {
        Toastify({
          text: $_('donation-deleted'),
          duration: 500,
          backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
        }).showToast();
        location.replace("./");
      })
      .catch((err) => {
        modal_open = true;
        delete_donor = original_data;
      });
  }
</script>

{#await promise}
  {$_('loading-donation-details')}
{:then}
  <section class="container p-5 select-none">
    <div class="flex flex-row mb-4">
      <div class="w-full">
        <nav class="w-full flex">
          <ol class="list-none flex flex-row items-center justify-start">
            <li class="flex items-center">
              <svg
                fill="currentColor"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                width="24"
                height="24"><path fill="none" d="M0 0h24v24H0z" />
                <path
                  d="M14 2a8 8 0 013.3 15.3A8 8 0 116.7 6.7 8 8 0 0114 2zm-3 7H9v1a2.5 2.5 0 00-.16 5h2.25a.5.5 0 010 1H7v2h2v1h2v-1a2.5 2.5 0 00.16-5H8.91a.5.5 0 010-1H13v-2h-2V9zm3-5a5.99 5.99 0 00-4.48 2.01 8 8 0 018.47 8.47A6 6 0 0014 4z" /></svg>
            </li>
            <li class="flex items-center ml-2">
              <a class="mr-2" href="./">{$_('donations')}</a><svg
                stroke="currentColor"
                fill="none"
                stroke-width="2"
                viewBox="0 0 24 24"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="h-3 w-3 mr-2 stroke-current"
                height="1em"
                width="1em"
                xmlns="http://www.w3.org/2000/svg"><line
                  x1="5"
                  y1="12"
                  x2="19"
                  y2="12" />
                <polyline points="12 5 19 12 12 19" /></svg>
            </li>
            <li class="flex items-center">
              <span class="mr-2">{original_data.id}</span>
            </li>
          </ol>
        </nav>
      </div>
    </div>
    <div class="mb-8 text-3xl font-extrabold leading-tight">
      {original_data.donor.firstname}
      {original_data.donor.middlename || ''}
      {original_data.donor.lastname}
      &gt;
      {#if original_data.responseType == 'DISTANCEDONATION'}
        {original_data.runner.firstname}
        {original_data.runner.middlename || ''}
        {original_data.runner.lastname}
      {:else}
        {$_('fixed-donation')}:
        {amount_input.toFixed(2).toLocaleString('de-DE', { valute: 'EUR' })}€
      {/if}
      <span data-id="donation_actions_${original_data.id}">
        {#if store.state.jwtinfo.userdetails.permissions.includes('DONATION:DELETE')}
          {#if delete_triggered}
            <button
              on:click={deleteDonation}
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:">{$_('confirm-deletion')}</button>
            <button
              on:click={() => {
                delete_triggered = !delete_triggered;
              }}
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-400 text-base font-medium text-white sm:w-auto sm:">{$_('cancel')}</button>
          {/if}
          {#if !delete_triggered}
            <button
              on:click={() => {
                delete_triggered = true;
              }}
              type="button"
              class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:">{$_('delete-donation')}</button>
          {/if}
        {/if}
        {#if !delete_triggered}
          <button
            disabled={!save_enabled}
            class:opacity-50={!save_enabled}
            type="button"
            on:click={submit}
            class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:">{$_('save-changes')}</button>
        {/if}
      </span>
    </div>
    <!--  -->
    <div>
      <span
        class="font-medium text-gray-700">{$_('total-donation-amount')}:</span>
      <span>{(editable.amount / 100)
          .toFixed(2)
          .toLocaleString('de-DE', { valute: 'EUR' })}€</span>
      |
      <span
        class="font-medium text-gray-700">{$_('paid-amount')}:</span>
      <span>{(editable.paidAmount / 100)
          .toFixed(2)
          .toLocaleString('de-DE', { valute: 'EUR' })}€</span>
      |
      <span
        class="font-medium text-gray-700">{$_('status')}:</span>
        {#if editable.status =="PAID"}
          <span
            class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">{$_('paid')}</span>
        {:else}
          <span
            class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">{$_('open')}</span>
        {/if}
    </div>
    <br>
    <div class=" w-full">
      <label
        for="donor"
        class="block  font-medium text-gray-700">{$_('donor')}</label>
      <Select
        containerClasses="rounded-l-md mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 rounded-md p-2"
        itemFilter={(label, filterText, option) => filterDonors(label, filterText, option)}
        items={current_donors}
        showChevron={true}
        placeholder={$_('search-for-donor-name-or-id')}
        noOptionsMessage={$_('no-donors-found')}
        bind:selectedValue={donor}
        on:select={(selectedValue) => {editable.donor = selectedValue.detail.value; editable.donor.donationAmount=original_data.donor.donationAmount; editable.donor.paidDonationAmount =original_data.donor.paidDonationAmount}}
        on:clear={() => (editable.donor = null)} />
    </div>
    {#if original_data.responseType == 'DISTANCEDONATION'}
      <div class=" w-full">
        <label
          for="donor"
          class="block  font-medium text-gray-700">{$_('runner')}</label>
        <Select
          containerClasses="rounded-l-md mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 rounded-md p-2"
          itemFilter={(label, filterText, option) => filterDonors(label, filterText, option)}
          items={current_runners}
          showChevron={true}
          placeholder={$_('search-for-runner-by-name-or-id')}
          noOptionsMessage={$_('no-runners-found')}
          bind:selectedValue={runner}
          on:select={(selectedValue) => (editable.runner = selectedValue.detail.value)}
          on:clear={() => (editable.runner = null)} />
      </div>
    {/if}
    <div class=" w-full">
      <label for="lastname" class="font-medium text-gray-700">
        {#if original_data.responseType == 'DISTANCEDONATION'}
          {$_('amount-per-kilometer')}
        {:else}{$_('donation-amount')}{/if}
      </label>
      <div class="mt-1 flex rounded-md shadow-sm">
        <input
          autocomplete="off"
          class:border-red-500={!is_amount_valid}
          class:focus:border-red-500={!is_amount_valid}
          class:focus:ring-red-500={!is_amount_valid}
          bind:value={amount_input}
          type="number"
          step="0.01"
          name="donation_amount_eur"
          class="focus:ring-indigo-500 focus:border-indigo-500 flex-1 block w-full rounded-none rounded-l-md sm: border-gray-300 border bg-gray-50 text-gray-500 p-2"
          placeholder="2.00" />
        <span
          class="inline-flex items-center px-3 rounded-r-md border border-gray-300 bg-gray-50 text-gray-500 ">€</span>
      </div>
      {#if !is_amount_valid}
        <span
          class="flex items-center font-medium tracking-wide text-red-500 text-xs mt-1 ml-1">
          {$_('donation-amount-must-be-greater-that-0-00eur')}
        </span>
      {/if}
    </div>
    <div class="w-full">
      <label
        for="token"
        class="block text-sm font-medium text-gray-700">{$_('paid-amount')}</label>
      <div class="inline-flex border-gray-300 border rounded-l-md rounded-r-md bg-gray-50 text-gray-500 w-full">
        <input
            autocomplete="off"
            class:border-red-500={!is_amount_valid}
            class:focus:border-red-500={!is_amount_valid}
            class:focus:ring-red-500={!is_amount_valid}
            bind:value={paid_amount_input}
            type="number"
            step="0.01"
            name="donation_amount_eur"
            class="focus:ring-indigo-500 focus:border-indigo-500 flex-1 block w-full rounded-none rounded-l-md sm:text-sm p-2"
            placeholder="2.00" />
          <button
            on:click={
              ()=>{
                paid_amount_input=paid_amount_input = (original_data.amount/100).toFixed(2);
              }
            }
            class="inline-flex items-center p-r-2 text-indigo-300 hover:text-indigo-700 text-sm">MAX</button>
          <span
            class="inline-flex items-center px-3 rounded-r-md border border-gray-300 bg-gray-50 text-gray-500 text-sm">€</span>
        </div>
        {#if !is_paid_amount_valid}
          <span
            class="flex items-center font-medium tracking-wide text-red-500 text-xs mt-1 ml-1">
            {$_('payment-amount-must-be-greater-than-0-00eur')}
          </span>
        {/if}
    </div>
  </section>
{:catch error}
  <PromiseError {error} />
{/await}
