<template>
  <QuickNav selected="Home"></QuickNav>
  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <!-- Breadcrumb -->
    <div id="ViewBreadcrumb" class="mb-8">
      <h1 class="text-lg text-center font-light relative px-7">
        <!-- Back -->
        <router-link
          :to="{ name: 'home' }"
          class="text-lg text-center px-2 py-1 absolute -left-2 -top-1"
          ><font-awesome icon="chevron-left" class="fa-fw"></font-awesome>
        </router-link>
        Given by...
      </h1>
    </div>

    <!-- Results List -->
    <ul class="border-t border-slate-300">
      <li class="border-b border-slate-300 py-3">
        <h2 class="text-base flex gap-4 items-center">
          <span class="grow">
            <img
              src="../assets/blank-square.svg"
              width="32"
              class="inline-block align-middle border border-slate-300 rounded-md mr-1"
            />
            Unnamed/Unknown
          </span>
          <span class="text-right">
            <button
              type="button"
              class="block w-full text-center text-sm uppercase 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-3 py-1.5 rounded-md"
              @click="openDialog()"
            >
              <font-awesome icon="gift" class="fa-fw"></font-awesome>
            </button>
          </span>
        </h2>
      </li>
      <li
        v-for="contact in allContacts"
        :key="contact.did"
        class="border-b border-slate-300 py-3"
      >
        <h2 class="text-base flex gap-4 items-center">
          <span class="grow font-semibold">
            <EntityIcon
              :contact="contact"
              :icon-size="32"
              class="inline-block align-middle border border-slate-300 rounded-md mr-1"
            />
            {{ contact.name || "(no name)" }}
          </span>
          <span class="text-right">
            <button
              type="button"
              class="block w-full text-center text-sm uppercase 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-3 py-1.5 rounded-md"
              @click="openDialog(contact)"
            >
              <font-awesome icon="gift" class="fa-fw"></font-awesome>
            </button>
          </span>
        </h2>
      </li>
    </ul>

    <GiftedDialog ref="customDialog" :to-project-id="projectId" />
  </section>
</template>

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

import GiftedDialog from "../components/GiftedDialog.vue";
import QuickNav from "../components/QuickNav.vue";
import EntityIcon from "../components/EntityIcon.vue";
import { NotificationIface } from "../constants/app";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import { Contact } from "../db/tables/contacts";
import { GiverReceiverInputInfo } from "../libs/util";

@Component({
  components: { GiftedDialog, QuickNav, EntityIcon },
})
export default class ContactGiftingView extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;
  $route!: RouteLocationNormalizedLoaded;
  $router!: Router;

  activeDid = "";
  allContacts: Array<Contact> = [];
  apiServer = "";
  description = "";
  projectId = "";
  prompt = "";

  async created() {
    try {
      const settings = await retrieveSettingsForActiveAccount();
      this.apiServer = settings.apiServer || "";
      this.activeDid = settings.activeDid || "";

      // .orderBy("name") wouldn't retrieve any entries with a blank name
      // .toCollection.sortBy("name") didn't sort in an order I understood
      const baseContacts = await db.contacts.toArray();
      this.allContacts = baseContacts.sort((a, b) =>
        (a.name || "").localeCompare(b.name || ""),
      );

      this.projectId = (this.$route.query["projectId"] as string) || "";
      this.prompt = (this.$route.query["prompt"] as string) ?? this.prompt;

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.error("Error retrieving settings & contacts:", err);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error",
          text:
            err.message ||
            "There was an error retrieving your settings or contacts.",
        },
        5000,
      );
    }
  }

  openDialog(giver?: GiverReceiverInputInfo) {
    const recipient = this.projectId
      ? undefined
      : { did: this.activeDid, name: "you" };
    (this.$refs.customDialog as GiftedDialog).open(
      giver,
      recipient,
      undefined,
      "Given by " + (giver?.name || "someone not named"),
      this.prompt,
    );
  }
}
</script>
