<template>
  <div>
    <div class="space-y-4">
      <!-- Loading State -->
      <div
        v-if="isLoading"
        class="mt-16 text-center text-4xl bg-slate-400 text-white w-14 py-2.5 rounded-full mx-auto"
      >
        <font-awesome icon="spinner" class="fa-spin-pulse" />
      </div>

      <!-- Members List -->

      <div v-else>
        <div class="text-center text-red-600 my-4">
          {{ decryptionErrorMessage() }}
        </div>

        <div v-if="missingMyself" class="py-4 text-red-600">
          You are not currently admitted by the organizer.
        </div>
        <div v-if="!firstName" class="py-4 text-red-600">
          Your name is not set, so others may not recognize you. Reload this
          page to set it.
        </div>

        <ul class="list-disc text-sm ps-4 space-y-2 mb-4">
          <li
            v-if="
              membersToShow().length > 0 && showOrganizerTools && isOrganizer
            "
          >
            Click
            <font-awesome icon="circle-plus" class="text-blue-500 text-sm" />
            /
            <font-awesome icon="circle-minus" class="text-rose-500 text-sm" />
            to add/remove them to/from the meeting.
          </li>
          <li
            v-if="
              membersToShow().length > 0 && getNonContactMembers().length > 0
            "
          >
            Click
            <font-awesome icon="circle-user" class="text-green-600 text-sm" />
            to add them to your contacts.
          </li>
        </ul>

        <div class="flex justify-between">
          <!-- 
        always have at least one refresh button even without members in case the organizer 
         changes the password 
         -->
          <button
            class="text-sm 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-3 py-1.5 rounded-md"
            title="Refresh members list now"
            @click="refreshData(false)"
          >
            <font-awesome icon="rotate" :class="{ 'fa-spin': isLoading }" />
            Refresh
            <span class="text-xs">({{ countdownTimer }}s)</span>
          </button>
        </div>
        <ul
          v-if="membersToShow().length > 0"
          class="border-t border-slate-300 my-2"
        >
          <li
            v-for="member in membersToShow()"
            :key="member.member.memberId"
            :class="[
              'border-b px-2 sm:px-3 py-1.5',
              {
                'bg-blue-50 border-t border-blue-300 -mt-[1px]':
                  !member.member.admitted &&
                  (isOrganizer || member.did === activeDid),
              },
              { 'border-slate-300': member.member.admitted },
            ]"
          >
            <div class="flex items-center gap-2 justify-between">
              <div class="flex items-center gap-1 overflow-hidden">
                <h3
                  :class="[
                    'font-semibold truncate',
                    {
                      'text-slate-500':
                        !member.member.admitted &&
                        (isOrganizer || member.did === activeDid),
                    },
                  ]"
                >
                  <font-awesome
                    v-if="member.member.memberId === members[0]?.memberId"
                    icon="crown"
                    class="fa-fw text-amber-400"
                  />
                  <font-awesome
                    v-if="member.did === activeDid"
                    icon="hand"
                    class="fa-fw text-slate-500"
                  />
                  <font-awesome
                    v-if="
                      !member.member.admitted &&
                      (isOrganizer || member.did === activeDid)
                    "
                    icon="hourglass-half"
                    class="fa-fw text-slate-400"
                  />
                  {{ member.name || unnamedMember }}
                </h3>
                <div
                  v-if="!getContactFor(member.did) && member.did !== activeDid"
                  class="flex items-center gap-1.5 ml-2 ms-1"
                >
                  <button
                    class="btn-add-contact ml-2"
                    title="Add as contact"
                    @click="addAsContact(member)"
                  >
                    <font-awesome icon="circle-user" />
                  </button>

                  <button
                    class="btn-info-contact ml-2"
                    title="Contact Info"
                    @click="
                      informAboutAddingContact(
                        getContactFor(member.did) !== undefined,
                      )
                    "
                  >
                    <font-awesome icon="circle-info" />
                  </button>
                </div>
                <div
                  v-if="getContactFor(member.did) && member.did !== activeDid"
                  class="flex items-center gap-1.5 ms-1"
                >
                  <router-link
                    :to="{ name: 'contact-edit', params: { did: member.did } }"
                  >
                    <font-awesome
                      icon="pen"
                      class="text-sm text-blue-500 ml-2 mb-1"
                    />
                  </router-link>
                  <router-link
                    :to="{ name: 'did', params: { did: member.did } }"
                  >
                    <font-awesome
                      icon="arrow-up-right-from-square"
                      class="text-sm text-blue-500 ml-2 mb-1"
                    />
                  </router-link>
                </div>
              </div>
              <span
                v-if="
                  showOrganizerTools && isOrganizer && member.did !== activeDid
                "
                class="flex items-center gap-1.5"
              >
                <button
                  :class="
                    member.member.admitted
                      ? 'btn-admission-remove'
                      : 'btn-admission-add'
                  "
                  :title="
                    member.member.admitted ? 'Remove member' : 'Admit member'
                  "
                  @click="checkWhetherContactBeforeAdmitting(member)"
                >
                  <font-awesome
                    :icon="
                      member.member.admitted ? 'circle-minus' : 'circle-plus'
                    "
                  />
                </button>

                <button
                  class="btn-info-admission"
                  title="Admission Info"
                  @click="informAboutAdmission()"
                >
                  <font-awesome icon="circle-info" />
                </button>
              </span>
            </div>
            <p class="text-xs text-gray-600 truncate">
              {{ member.did }}
            </p>
          </li>
        </ul>

        <div v-if="membersToShow().length > 0" class="flex justify-between">
          <!-- 
        always have at least one refresh button even without members in case the organizer 
         changes the password 
         -->
          <button
            class="text-sm 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-3 py-1.5 rounded-md"
            title="Refresh members list now"
            @click="refreshData(false)"
          >
            <font-awesome icon="rotate" :class="{ 'fa-spin': isLoading }" />
            Refresh
            <span class="text-xs">({{ countdownTimer }}s)</span>
          </button>
        </div>

        <p v-if="members.length === 0" class="text-gray-500 py-4">
          No members have joined this meeting yet
        </p>
      </div>
    </div>

    <!-- Bulk Members Dialog for both admitting and setting visibility -->
    <BulkMembersDialog
      ref="bulkMembersDialog"
      :active-did="activeDid"
      :api-server="apiServer"
      :is-organizer="isOrganizer"
      @close="closeBulkMembersDialogCallback"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Emit } from "vue-facing-decorator";

import { NotificationIface } from "@/constants/app";
import {
  NOTIFY_ADD_CONTACT_FIRST,
  NOTIFY_CONTINUE_WITHOUT_ADDING,
} from "@/constants/notifications";
import { SOMEONE_UNNAMED } from "@/constants/entities";
import {
  errorStringForLog,
  getHeaders,
  register,
  serverMessageForUser,
} from "@/libs/endorserServer";
import { decryptMessage } from "@/libs/crypto";
import { Contact } from "@/db/tables/contacts";
import { MemberData } from "@/interfaces";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { createNotifyHelpers, TIMEOUTS } from "@/utils/notify";
import BulkMembersDialog from "./BulkMembersDialog.vue";

interface Member {
  admitted: boolean;
  content: string;
  memberId: number;
}

interface DecryptedMember {
  member: Member;
  name: string;
  did: string;
  isRegistered: boolean;
}

@Component({
  components: {
    BulkMembersDialog,
  },
  mixins: [PlatformServiceMixin],
})
export default class MembersList extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;

  notify!: ReturnType<typeof createNotifyHelpers>;

  @Prop({ required: true }) password!: string;
  @Prop({ default: false }) showOrganizerTools!: boolean;

  // Emit methods using @Emit decorator
  @Emit("error")
  emitError(message: string) {
    return message;
  }

  contacts: Array<Contact> = [];
  decryptedMembers: DecryptedMember[] = [];
  firstName = "";
  isLoading = true;
  isOrganizer = false;
  members: Member[] = [];
  missingPassword = false;
  missingMyself = false;
  activeDid = "";
  apiServer = "";

  // Auto-refresh functionality
  countdownTimer = 10;
  autoRefreshInterval: NodeJS.Timeout | null = null;
  lastRefreshTime = 0;
  previousMemberDidsIgnored: string[] = [];

  /**
   * Get the unnamed member constant
   */
  get unnamedMember(): string {
    return SOMEONE_UNNAMED;
  }

  async created() {
    this.notify = createNotifyHelpers(this.$notify);

    const settings = await this.$accountSettings();

    // Get activeDid from active_identity table (single source of truth)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const activeIdentity = await (this as any).$getActiveIdentity();
    this.activeDid = activeIdentity.activeDid || "";

    this.apiServer = settings.apiServer || "";
    this.firstName = settings.firstName || "";

    this.refreshData();
  }

  async fetchMembers() {
    try {
      this.isLoading = true;
      const headers = await getHeaders(this.activeDid);
      const response = await this.axios.get(
        `${this.apiServer}/api/partner/groupOnboardMembers`,
        { headers },
      );

      if (response.data && response.data.data) {
        this.members = response.data.data;
        await this.decryptMemberContents();
      }
    } catch (error) {
      this.$logAndConsole(
        "Error fetching members: " + errorStringForLog(error),
        true,
      );
      this.emitError(serverMessageForUser(error) || "Failed to fetch members.");
    } finally {
      this.isLoading = false;
    }
  }

  async decryptMemberContents() {
    this.decryptedMembers = [];

    if (!this.password) {
      this.missingPassword = true;
      return;
    }

    let isFirstEntry = true,
      foundMyself = false;
    for (const member of this.members) {
      try {
        const decryptedContent = await decryptMessage(
          member.content,
          this.password,
        );
        const content = JSON.parse(decryptedContent);

        this.decryptedMembers.push({
          member: {
            ...member,
            admitted: member.admitted !== undefined ? member.admitted : true, // Default to true for non-organizers
          },
          name: content.name,
          did: content.did,
          isRegistered: !!content.isRegistered,
        });
        if (isFirstEntry && content.did === this.activeDid) {
          this.isOrganizer = true;
        }
        if (content.did === this.activeDid) {
          foundMyself = true;
        }
      } catch (error) {
        // do nothing, relying on the count of members to determine if there was an error
      }
      isFirstEntry = false;
    }
    this.missingMyself = !foundMyself;
  }

  decryptionErrorMessage(): string {
    if (this.isOrganizer) {
      if (this.decryptedMembers.length < this.members.length) {
        return "Some members have data that cannot be decrypted with that password.";
      } else {
        // the lists must be equal
        return "";
      }
    } else {
      // non-organizers should only see problems if the first (organizer) member is not decrypted
      if (
        this.decryptedMembers.length === 0 ||
        this.decryptedMembers[0].member.memberId !== this.members[0].memberId
      ) {
        return "Your password is not the same as the organizer. Retry or have them check their password.";
      } else {
        // the first (organizer) member was decrypted OK
        return "";
      }
    }
  }

  membersToShow(): DecryptedMember[] {
    let members: DecryptedMember[] = [];

    if (this.isOrganizer) {
      if (this.showOrganizerTools) {
        members = this.decryptedMembers;
      } else {
        members = this.decryptedMembers.filter(
          (member: DecryptedMember) => member.member.admitted,
        );
      }
    } else {
      // non-organizers only get visible members from server, plus themselves

      // Check if current user is already in the decrypted members list
      if (
        !this.decryptedMembers.find((member) => member.did === this.activeDid)
      ) {
        // this is a stub for this user just in case they are waiting to get in
        // which is especially useful so they can see their own DID
        const currentUser: DecryptedMember = {
          member: {
            admitted: false,
            content: "{}",
            memberId: -1,
          },
          name: this.firstName,
          did: this.activeDid,
          isRegistered: false,
        };
        members = [currentUser, ...this.decryptedMembers];
      } else {
        members = this.decryptedMembers;
      }
    }

    // Sort members according to priority:
    // 1. Organizer at the top
    // 2. Current user next
    // 3. Non-admitted members next
    // 4. Everyone else after
    return members.sort((a, b) => {
      // Check if either member is the organizer (first member in original list)
      const aIsOrganizer = a.member.memberId === this.members[0]?.memberId;
      const bIsOrganizer = b.member.memberId === this.members[0]?.memberId;

      // Check if either member is the current user
      const aIsCurrentUser = a.did === this.activeDid;
      const bIsCurrentUser = b.did === this.activeDid;

      // Organizer always comes first
      if (aIsOrganizer && !bIsOrganizer) return -1;
      if (!aIsOrganizer && bIsOrganizer) return 1;

      // If both are organizers, maintain original order
      if (aIsOrganizer && bIsOrganizer) return 0;

      // Current user comes second (after organizer)
      if (aIsCurrentUser && !bIsCurrentUser && !bIsOrganizer) return -1;
      if (!aIsCurrentUser && bIsCurrentUser && !aIsOrganizer) return 1;

      // If both are current users, maintain original order
      if (aIsCurrentUser && bIsCurrentUser) return 0;

      // Non-admitted members come before admitted members
      if (!a.member.admitted && b.member.admitted) return -1;
      if (a.member.admitted && !b.member.admitted) return 1;

      // If admission status is the same, maintain original order
      return 0;
    });
  }

  informAboutAdmission() {
    this.notify.info(
      "This is to register people in Time Safari and to admit them to the meeting. A (+) symbol means they are not yet admitted and you can register and admit them. A (-) symbol means you can remove them, but they will stay registered.",
      TIMEOUTS.VERY_LONG,
    );
  }

  informAboutAddingContact(contactImportedAlready: boolean) {
    if (contactImportedAlready) {
      this.notify.info(
        "They are in your contacts. To remove them, use the contacts page.",
        TIMEOUTS.VERY_LONG,
      );
    } else {
      this.notify.info(
        "This is to add them to your contacts. To remove them later, use the contacts page.",
        TIMEOUTS.VERY_LONG,
      );
    }
  }

  getContactFor(did: string): Contact | undefined {
    return this.contacts.find((contact) => contact.did === did);
  }

  getPendingMembersToAdmit(): MemberData[] {
    return this.decryptedMembers
      .filter(
        (member) => member.did !== this.activeDid && !member.member.admitted,
      )
      .map(this.convertDecryptedMemberToMemberData);
  }

  getNonContactMembers(): MemberData[] {
    return this.decryptedMembers
      .filter(
        (member) =>
          member.did !== this.activeDid && !this.getContactFor(member.did),
      )
      .map(this.convertDecryptedMemberToMemberData);
  }

  convertDecryptedMemberToMemberData(
    decryptedMember: DecryptedMember,
  ): MemberData {
    return {
      did: decryptedMember.did,
      name: decryptedMember.name,
      isContact: !!this.getContactFor(decryptedMember.did),
      member: {
        memberId: decryptedMember.member.memberId.toString(),
      },
    };
  }

  /**
   * Show the bulk members dialog if conditions are met
   * (admit pending members for organizers, add to contacts for non-organizers)
   */
  async refreshData(bypassPromptIfAllWereIgnored = true) {
    // Force refresh both contacts and members
    this.contacts = await this.$getAllContacts();
    await this.fetchMembers();

    const pendingMembers = this.isOrganizer
      ? this.getPendingMembersToAdmit()
      : this.getNonContactMembers();
    if (pendingMembers.length === 0) {
      this.startAutoRefresh();
      return;
    }
    if (bypassPromptIfAllWereIgnored) {
      // only show if there are members that have not been ignored
      const pendingMembersNotIgnored = pendingMembers.filter(
        (member) => !this.previousMemberDidsIgnored.includes(member.did),
      );
      if (pendingMembersNotIgnored.length === 0) {
        this.startAutoRefresh();
        // everyone waiting has been ignored
        return;
      }
    }
    this.stopAutoRefresh();
    (this.$refs.bulkMembersDialog as BulkMembersDialog).open(pendingMembers);
  }

  // Bulk Members Dialog methods
  async closeBulkMembersDialogCallback(
    result: { notSelectedMemberDids: string[] } | undefined,
  ) {
    this.previousMemberDidsIgnored = result?.notSelectedMemberDids || [];

    await this.refreshData();
  }

  checkWhetherContactBeforeAdmitting(decrMember: DecryptedMember) {
    const contact = this.getContactFor(decrMember.did);
    if (!decrMember.member.admitted && !contact) {
      // If not a contact, stop auto-refresh and show confirmation dialog
      this.stopAutoRefresh();
      this.$notify(
        {
          group: "modal",
          type: "confirm",
          title: NOTIFY_ADD_CONTACT_FIRST.title,
          text: NOTIFY_ADD_CONTACT_FIRST.text,
          yesText: NOTIFY_ADD_CONTACT_FIRST.yesText,
          noText: NOTIFY_ADD_CONTACT_FIRST.noText,
          onYes: async () => {
            await this.addAsContact(decrMember);
            // After adding as contact, proceed with admission
            await this.toggleAdmission(decrMember);
            this.startAutoRefresh();
          },
          onNo: async () => {
            // If they choose not to add as contact, show second confirmation
            this.$notify(
              {
                group: "modal",
                type: "confirm",
                title: NOTIFY_CONTINUE_WITHOUT_ADDING.title,
                text: NOTIFY_CONTINUE_WITHOUT_ADDING.text,
                yesText: NOTIFY_CONTINUE_WITHOUT_ADDING.yesText,
                onYes: async () => {
                  await this.toggleAdmission(decrMember);
                  this.startAutoRefresh();
                },
                onCancel: async () => {
                  // Do nothing, effectively canceling the operation
                  this.startAutoRefresh();
                },
              },
              TIMEOUTS.MODAL,
            );
          },
          onCancel: async () => {
            this.startAutoRefresh();
          },
        },
        TIMEOUTS.MODAL,
      );
    } else {
      // If already a contact, proceed directly with admission
      this.toggleAdmission(decrMember);
    }
  }

  async toggleAdmission(decrMember: DecryptedMember) {
    try {
      const headers = await getHeaders(this.activeDid);
      await this.axios.put(
        `${this.apiServer}/api/partner/groupOnboardMember/${decrMember.member.memberId}`,
        { admitted: !decrMember.member.admitted },
        { headers },
      );
      // Update local state
      decrMember.member.admitted = !decrMember.member.admitted;

      const oldContact = this.getContactFor(decrMember.did);
      // if admitted, now register that user if they are not registered
      if (
        decrMember.member.admitted &&
        !decrMember.isRegistered &&
        !oldContact?.registered
      ) {
        const contactOldOrNew: Contact = oldContact || {
          did: decrMember.did,
          name: decrMember.name,
        };
        try {
          const result = await register(
            this.activeDid,
            this.apiServer,
            this.axios,
            contactOldOrNew,
          );
          if (result.success) {
            decrMember.isRegistered = true;
            if (oldContact) {
              await this.$updateContact(decrMember.did, { registered: true });
              oldContact.registered = true;
            }
            this.notify.success(
              "Besides being admitted, they were also registered.",
              TIMEOUTS.STANDARD,
            );
          } else {
            throw result;
          }
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
        } catch (error: any) {
          // registration failure is likely explained by a message from the server$notif
          const additionalInfo =
            serverMessageForUser(error) || error?.error || "";
          this.notify.warning(
            "They were admitted to the meeting. However, registration failed. You can register them from the contacts screen. " +
              additionalInfo,
            TIMEOUTS.VERY_LONG,
          );
        }
      }
    } catch (error) {
      this.$logAndConsole(
        "Error toggling admission: " + errorStringForLog(error),
        true,
      );
      this.emitError(
        serverMessageForUser(error) ||
          "Failed to update member admission status.",
      );
    }
  }

  async addAsContact(member: DecryptedMember) {
    try {
      const newContact = {
        did: member.did,
        name: member.name,
      };

      await this.$insertContact(newContact);
      this.contacts.push(newContact);

      this.notify.success(
        "They were added to your contacts.",
        TIMEOUTS.STANDARD,
      );
    } catch (err) {
      this.$logAndConsole(
        "Error adding contact: " + errorStringForLog(err),
        true,
      );
      let message = "An error prevented adding this contact.";
      if (err instanceof Error && err.message?.indexOf("already exists") > -1) {
        message = "This person is already in your contact list.";
      }
      this.notify.error(message, TIMEOUTS.LONG);
    }
  }

  startAutoRefresh() {
    this.stopAutoRefresh();
    this.lastRefreshTime = Date.now();
    this.countdownTimer = 10;

    this.autoRefreshInterval = setInterval(() => {
      const now = Date.now();
      const timeSinceLastRefresh = (now - this.lastRefreshTime) / 1000;

      if (timeSinceLastRefresh >= 10) {
        // Time to refresh
        this.refreshData();
        this.lastRefreshTime = now;
        this.countdownTimer = 10;
      } else {
        // Update countdown
        this.countdownTimer = Math.max(
          0,
          Math.round(10 - timeSinceLastRefresh),
        );
      }
    }, 1000); // Update every second
  }

  stopAutoRefresh() {
    if (this.autoRefreshInterval) {
      clearInterval(this.autoRefreshInterval);
      this.autoRefreshInterval = null;
    }
  }

  beforeDestroy() {
    this.stopAutoRefresh();
  }
}
</script>

<style scoped>
/* Button Classes */
.btn-action-refresh {
  /* stylelint-disable-next-line at-rule-no-unknown */
  @apply w-8 h-8 flex items-center justify-center rounded-full 
    bg-blue-100 text-blue-600 hover:bg-blue-200 hover:text-blue-800 
    transition-colors;
}

.btn-add-contact {
  /* stylelint-disable-next-line at-rule-no-unknown */
  @apply text-lg text-green-600 hover:text-green-800 
    transition-colors;
}

.btn-info-contact,
.btn-info-admission {
  /* stylelint-disable-next-line at-rule-no-unknown */
  @apply text-slate-400 hover:text-slate-600 
    transition-colors;
}

.btn-admission-add {
  /* stylelint-disable-next-line at-rule-no-unknown */
  @apply text-lg text-blue-500 hover:text-blue-700 
    transition-colors;
}

.btn-admission-remove {
  /* stylelint-disable-next-line at-rule-no-unknown */
  @apply text-lg text-rose-500 hover:text-rose-700 
    transition-colors;
}
</style>
