<template>
  <QuickNav />
  <TopMessage />

  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- Back -->
    <div class="text-lg text-center font-light relative px-7">
      <h1
        class="text-lg text-center px-2 py-1 absolute -left-2 -top-1"
        @click="$router.back()"
      >
        <fa icon="chevron-left" class="fa-fw"></fa>
      </h1>
    </div>

    <!-- Heading -->
    <h1 id="ViewHeading" class="text-4xl text-center font-light px-4 mb-4">
      Beginning of BVC Saturday Meeting
    </h1>

    <div>
      <h2 class="text-2xl m-2">You're Here</h2>
      <div class="m-2 flex">
        <input type="checkbox" v-model="attended" class="h-6 w-6" />
        <span class="pb-2 pl-2 pr-2">Attended</span>
      </div>
      <div class="m-2 flex">
        <input type="checkbox" v-model="gaveTime" class="h-6 w-6" />
        <span class="pb-2 pl-2 pr-2">Spent Time</span>
        <span v-if="gaveTime">
          <input
            type="text"
            placeholder="How much time"
            v-model="hoursStr"
            size="1"
            class="border border-slate-400 h-6 px-2"
          />
          hour(s)
        </span>
        <!-- This is to match input height to avoid shifting when hiding & showing. -->
        <span v-else class="h-6" />
      </div>
    </div>

    <div
      v-if="attended || (gaveTime && hoursStr && hoursStr != '0')"
      class="flex justify-center mt-4"
    >
      <button
        @click="record()"
        class="block text-center text-md font-bold bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-2 py-3 rounded-md w-56"
      >
        Sign & Send
      </button>
    </div>
    <div v-else class="flex justify-center mt-4">
      <button
        class="block text-center text-md font-bold bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-2 py-3 rounded-md w-56"
      >
        Select Your Actions
      </button>
    </div>
  </section>
</template>

<script lang="ts">
import axios from "axios";
import { DateTime } from "luxon";
import { Router } from "vue-router";
import { Component, Vue } from "vue-facing-decorator";

import QuickNav from "@/components/QuickNav.vue";
import TopMessage from "@/components/TopMessage.vue";
import { NotificationIface } from "@/constants/app";
import { retrieveSettingsForActiveAccount } from "@/db/index";
import {
  BVC_MEETUPS_PROJECT_CLAIM_ID,
  bvcMeetingJoinClaim,
  createAndSubmitClaim,
  createAndSubmitGive,
} from "@/libs/endorserServer";
import * as libsUtil from "@/libs/util";

@Component({
  components: {
    QuickNav,
    TopMessage,
  },
})
export default class QuickActionBvcBeginView extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;

  attended = true;
  gaveTime = true;
  hoursStr = "1";
  todayOrPreviousStartDate = "";

  async mounted() {
    // use the time zone for Bountiful
    let currentOrPreviousSat = DateTime.now().setZone("America/Denver");
    if (currentOrPreviousSat.weekday < 6) {
      // it's not Saturday or Sunday,
      // so move back one week before setting to the Saturday
      currentOrPreviousSat = currentOrPreviousSat.minus({ week: 1 });
    }
    const eventStartDateObj = currentOrPreviousSat
      .set({ weekday: 6 })
      .set({ hour: 9 })
      .startOf("hour");

    // Hack, but full ISO pushes the length to 340 which crashes verifyJWT!
    this.todayOrPreviousStartDate =
      eventStartDateObj.toISO({
        suppressMilliseconds: true,
      }) || "";
  }

  async record() {
    const settings = await retrieveSettingsForActiveAccount();
    const activeDid = settings.activeDid || "";
    const apiServer = settings.apiServer || "";

    try {
      const hoursNum = libsUtil.numberOrZero(this.hoursStr);

      this.$notify({ group: "alert", type: "toast", title: "Sent..." }, 1000);

      // first send the claim for time given
      let timeSuccess = false;
      if (this.gaveTime && hoursNum > 0) {
        const timeResult = await createAndSubmitGive(
          axios,
          apiServer,
          activeDid,
          activeDid,
          undefined,
          undefined,
          hoursNum,
          "HUR",
          BVC_MEETUPS_PROJECT_CLAIM_ID,
        );
        if (timeResult.type === "success") {
          timeSuccess = true;
        } else {
          console.error("Error sending time:", timeResult);
          this.$notify(
            {
              group: "alert",
              type: "danger",
              title: "Error",
              text:
                timeResult?.error?.userMessage ||
                "There was an error sending the time.",
            },
            5000,
          );
        }
      }

      // now send the claim for attendance
      let attendedSuccess = false;
      if (this.attended) {
        const attendResult = await createAndSubmitClaim(
          bvcMeetingJoinClaim(activeDid, this.todayOrPreviousStartDate),
          activeDid,
          apiServer,
          axios,
        );
        if (attendResult.type === "success") {
          attendedSuccess = true;
        } else {
          console.error("Error sending attendance:", attendResult);
          this.$notify(
            {
              group: "alert",
              type: "danger",
              title: "Error",
              text:
                attendResult?.error?.userMessage ||
                "There was an error sending the attendance.",
            },
            5000,
          );
        }
      }

      if (timeSuccess || attendedSuccess) {
        const actions =
          timeSuccess && attendedSuccess
            ? "Your attendance and time have been recorded."
            : timeSuccess
              ? "Your time has been recorded."
              : "Your attendance has been recorded.";
        this.$notify(
          {
            group: "alert",
            type: "success",
            title: "Success",
            text: actions,
          },
          3000,
        );
        (this.$router as Router).push({ path: "/quick-action-bvc" });
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      console.error("Error sending claims.", error);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error",
          text: error.userMessage || "There was an error sending the claims.",
        },
        5000,
      );
    }
  }
}
</script>