<template>
  <QuickNav selected="Contacts" />

  <section id="Content" class="p-6 pb-24 max-w-3xl mx-auto">
    <TopMessage />

    <!-- Sub View Heading -->
    <div id="SubViewHeading" class="flex gap-4 items-start mb-8">
      <h1 class="grow text-xl text-center font-semibold leading-tight">
        Onboarding Meeting Admin
      </h1>

      <!-- Spacer (no Back button) -->
      <div class="order-first p-3 pe-3.5 pb-3.5"></div>

      <!-- Help button -->
      <router-link
        :to="{ name: 'help' }"
        class="block ms-auto text-sm text-center text-white bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] p-1.5 rounded-full"
      >
        <font-awesome icon="question" class="block text-center w-[1em]" />
      </router-link>
    </div>

    <!-- Existing Meeting Section -->
    <div
      v-if="!isLoading && currentMeeting != null && !isInEditOrCreateMode()"
      class="mt-8 p-4 border rounded-lg bg-white shadow"
    >
      <div class="flex items-center justify-between mb-4">
        <div class="flex items-center">
          <h2 class="text-2xl">Current Meeting</h2>
          <button
            class="mb-4 text-blue-600 hover:text-blue-800 transition-colors duration-200 ml-2"
            title="Edit Meeting"
            @click="startEditing"
          >
            <font-awesome icon="pen" class="fa-fw" />
            <span class="sr-only">{{
              isInCreateMode() ? "Create Meeting" : "Edit Meeting"
            }}</span>
          </button>
        </div>
        <button
          class="text-red-600 hover:text-red-800 transition-colors duration-200"
          :disabled="isDeleting"
          :class="{ 'opacity-50 cursor-not-allowed': isDeleting }"
          title="Delete Meeting"
          @click="confirmDelete"
        >
          <font-awesome icon="trash-can" class="fa-fw" />
          <span class="sr-only">{{
            isDeleting ? "Deleting..." : "Delete Meeting"
          }}</span>
        </button>
      </div>
      <div class="space-y-2">
        <p><strong>Name:</strong> {{ currentMeeting.name }}</p>
        <p>
          <strong>Expires:</strong>
          {{ formatExpirationTime(currentMeeting.expiresAt) }}
        </p>

        <div v-if="currentMeeting.password" class="mt-4">
          <p class="text-gray-600">
            Share the meeting name & password with the members, or send them the
            "Page for Members" link below.
          </p>
        </div>
        <div v-else class="text-red-600">
          You must reenter your password. Edit this meeting, or delete it and
          create a new meeting.
        </div>
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <div
      v-if="showDeleteConfirm"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4"
    >
      <div class="bg-white rounded-lg p-6 max-w-sm w-full">
        <h3 class="text-lg font-medium mb-4">Delete Meeting?</h3>
        <p class="text-gray-600 mb-6">
          This action cannot be undone. Are you sure you want to delete this
          meeting?
        </p>
        <div class="flex justify-between space-x-4">
          <button
            class="px-4 py-2 bg-slate-500 text-white rounded hover:bg-slate-700"
            @click="showDeleteConfirm = false"
          >
            Cancel
          </button>
          <button
            class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
            @click="deleteMeeting"
          >
            Delete
          </button>
        </div>
      </div>
    </div>

    <!-- Create/Edit Meeting Form -->
    <div
      v-if="
        !isLoading &&
        isInEditOrCreateMode() &&
        newOrUpdatedMeetingInputs !=
          null /* duplicate check is for typechecks */
      "
      class="mt-8"
    >
      <h2 class="text-2xl mb-4">
        {{ isInCreateMode() ? "Create New Meeting" : "Edit Meeting" }}
      </h2>
      <!-- 
      This is my first form. Not sure if I like it; will see if the browser benefits extend to 
      the native app.
      -->
      <form
        class="space-y-4"
        @submit.prevent="isInCreateMode() ? createMeeting() : updateMeeting()"
      >
        <div>
          <label
            for="meetingName"
            class="block text-sm font-medium text-gray-700"
            >Meeting Name</label
          >
          <input
            id="meetingName"
            v-model="newOrUpdatedMeetingInputs.name"
            type="text"
            required
            class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none"
            placeholder="Enter meeting name"
          />
        </div>

        <div>
          <label
            for="expirationTime"
            class="block text-sm font-medium text-gray-700"
            >Meeting Expiration Time</label
          >
          <input
            id="expirationTime"
            v-model="newOrUpdatedMeetingInputs.expiresAt"
            type="datetime-local"
            required
            :min="minDateTime"
            class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>

        <div>
          <label for="password" class="block text-sm font-medium text-gray-700"
            >Meeting Password</label
          >
          <input
            id="password"
            v-model="newOrUpdatedMeetingInputs.password"
            type="text"
            required
            class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none"
            placeholder="Enter meeting password"
          />
        </div>

        <div>
          <label for="userName" class="block text-sm font-medium text-gray-700"
            >Your Name</label
          >
          <input
            id="userName"
            v-model="newOrUpdatedMeetingInputs.userFullName"
            type="text"
            required
            class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:outline-none"
            placeholder="Your name"
          />
        </div>

        <div>
          <label
            for="projectLink"
            class="block text-sm font-medium text-gray-700 mb-1"
            >Project Link</label
          >
          <div class="w-full flex items-stretch">
            <div
              class="flex items-center gap-2 grow border border-slate-400 border-r-0 last:border-r px-3 py-2 rounded-l last:rounded overflow-hidden cursor-pointer hover:bg-slate-100"
              @click="openProjectLinkDialog"
            >
              <div>
                <ProjectIcon
                  v-if="selectedProject"
                  :entity-id="selectedProject.handleId"
                  :icon-size="30"
                  :image-url="selectedProject.image"
                  class="!size-[2rem] shrink-0 border border-slate-300 bg-white overflow-hidden rounded-full"
                />
                <font-awesome
                  v-else
                  icon="folder-open"
                  class="text-slate-400"
                />
              </div>
              <div class="overflow-hidden">
                <div
                  :class="{
                    'text-sm font-semibold': selectedProject,
                    'text-slate-400': !selectedProject,
                  }"
                  class="truncate"
                >
                  {{
                    selectedProject
                      ? selectedProject.name || "Unnamed Project"
                      : "Select Project…"
                  }}
                </div>
                <div
                  v-if="selectedProject"
                  class="text-xs text-slate-500 truncate"
                >
                  <font-awesome icon="user" class="text-slate-400" />
                  {{ selectedProjectIssuerName }}
                </div>
              </div>
            </div>
            <button
              v-if="selectedProject"
              class="text-rose-600 px-3 py-2 border border-slate-400 border-l-0 rounded-r hover:bg-rose-600 hover:text-white hover:border-rose-600"
              @click="unsetProjectLink"
            >
              <font-awesome icon="trash-can" />
            </button>
          </div>
        </div>

        <button
          type="submit"
          class="w-full bg-gradient-to-b from-green-400 to-green-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-4 py-2 rounded-md hover:from-green-500 hover:to-green-800"
          :disabled="isLoading"
        >
          {{
            isLoading
              ? isInCreateMode()
                ? "Creating..."
                : "Updating..."
              : isInCreateMode()
                ? "Create Meeting"
                : "Update Meeting"
          }}
        </button>
        <button
          v-if="isInEditOrCreateMode()"
          type="button"
          class="w-full bg-slate-500 text-white px-4 py-2 rounded-md hover:bg-slate-600"
          @click="cancelEditing"
        >
          Cancel
        </button>
      </form>
    </div>

    <MeetingProjectDialog
      ref="meetingProjectDialog"
      :active-did="activeDid"
      :all-my-dids="allMyDids"
      :all-contacts="allContacts"
      :notify="$notify"
      @assign="handleProjectLinkAssigned"
      @open="handleDialogOpen"
      @close="handleDialogClose"
    />

    <!-- Members Section -->
    <div
      v-if="!isLoading && currentMeeting != null && !!currentMeeting.password"
      class="mt-8 p-4 border rounded-lg bg-white shadow"
    >
      <div class="flex items-center justify-between">
        <h2 class="font-bold">Meeting Members</h2>
      </div>
      <ul class="list-disc text-sm mt-4 mb-2 ps-4 space-y-2">
        <li>
          Page for Members:
          <span
            class="ml-4 cursor-pointer text-blue-600"
            title="Click to copy link for members"
            @click="copyMembersLinkToClipboard"
          >
            <font-awesome icon="link" />
          </span>
          <a
            v-if="!!currentMeeting.password"
            :href="onboardMeetingMembersLink()"
            class="ml-4 text-blue-600"
            target="_blank"
          >
            <font-awesome icon="external-link" />
          </a>
        </li>
      </ul>

      <MeetingMembersList
        ref="membersList"
        :match-pairs="matchPairs"
        :password="currentMeeting.password || ''"
        :show-organizer-tools="true"
        class="mt-4"
        @error="handleMembersError"
      />
    </div>

    <div class="mt-8 p-4 border rounded-lg bg-white shadow">
      <!-- Pairwise matches (organizer only: this page is organizer's meeting) -->
      <div class="border-gray-200">
        <h3 class="font-semibold mb-2">Matching Pairs</h3>
        <div class="flex flex-wrap gap-2 mb-4">
          <button
            type="button"
            class="px-3 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            :disabled="isPostingMatch"
            @click="postNewMatchesThenRefresh()"
          >
            <font-awesome
              v-if="isPostingMatch"
              icon="spinner"
              class="fa-spin fa-fw"
            />
            Make New Matches
          </button>
          <button
            type="button"
            class="px-3 py-2 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
            :disabled="isPostingMatch || !matchPairs?.length"
            @click="clearMatchesThenRefresh()"
          >
            <font-awesome
              v-if="isPostingMatch"
              icon="spinner"
              class="fa-spin fa-fw"
            />
            Erase to Start Over
          </button>
        </div>
        <div v-if="isLoadingMatches" class="text-sm text-gray-500 py-2">
          <font-awesome icon="spinner" class="fa-spin fa-fw" />
          Loading matches…
        </div>
        <ul
          v-else-if="matchPairs && matchPairs.length > 0"
          class="list-none space-y-3 text-sm"
        >
          <li
            v-for="pair in matchPairs"
            :key="pair.pairNumber"
            class="p-3 rounded border border-gray-200 bg-gray-50"
          >
            <span class="font-medium">Pair {{ pair.pairNumber }}</span>
            <span class="text-gray-600">
              (similarity {{ pair.similarity.toFixed(2) }})</span
            >
            <ul class="mt-2 ml-2 space-y-1">
              <li
                v-for="p in pair.participants"
                :key="p.issuerDid"
                class="text-gray-700"
              >
                {{
                  p.decryptedContentObject?.name
                    ? p.decryptedContentObject.name
                    : "(No Name)"
                }}
                -
                {{
                  p.description
                    ? p.description.substring(0, 80) +
                      (p.description.length > 80 ? "…" : "")
                    : "(No Profile)"
                }}
              </li>
            </ul>
          </li>
        </ul>
        <p
          v-else-if="matchPairs && matchPairs.length === 0"
          class="text-sm text-gray-500 py-2"
        >
          No matches yet. Click “Get matches” to pair members by profile
          similarity.
        </p>
      </div>
    </div>

    <div
      v-if="currentMeeting?.projectLink"
      class="mt-8 p-4 border rounded-lg bg-white shadow"
    >
      <!-- Project Link Section -->
      <div>
        <router-link
          :to="'/project/' + encodeURIComponent(currentMeeting.projectLink)"
          class="text-blue-600 hover:text-blue-800 transition-colors duration-200"
        >
          Go To Project Page
        </router-link>
      </div>
    </div>

    <div v-else-if="isLoading">
      <div class="flex justify-center items-center h-full">
        <font-awesome icon="spinner" class="fa-spin-pulse" />
      </div>
    </div>
  </section>
</template>

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

import QuickNav from "../components/QuickNav.vue";
import TopMessage from "../components/TopMessage.vue";
import MeetingMembersList from "../components/MeetingMembersList.vue";
import MeetingMemberMatch from "../components/MeetingMemberMatch.vue";
import MeetingProjectDialog from "../components/MeetingProjectDialog.vue";
import ProjectIcon from "../components/ProjectIcon.vue";
import {
  errorStringForLog,
  getHeaders,
  serverMessageForUser,
  didInfo,
} from "../libs/endorserServer";
import { encryptMessage, decryptMessage } from "../libs/crypto";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { createNotifyHelpers, TIMEOUTS } from "@/utils/notify";
import { APP_SERVER } from "@/constants/app";
import {
  NOTIFY_MEETING_INVALID_TIME,
  NOTIFY_MEETING_NAME_REQUIRED,
  NOTIFY_MEETING_PASSWORD_REQUIRED,
  NOTIFY_MEETING_CREATED,
  NOTIFY_MEETING_DELETED,
  NOTIFY_MEETING_LINK_COPIED,
} from "@/constants/notifications";
import { PlanData } from "../interfaces/records";
import { Contact } from "../db/tables/contacts";
import { AxiosErrorResponse, MatchPair } from "@/interfaces";
interface ServerMeeting {
  groupId: number; // from the server
  name: string; // to & from the server
  expiresAt: string; // to & from the server
  userFullName?: string; // from the user's session
  password?: string; // from the user's session
  projectLink?: string; // to & from the server
}

interface MeetingSetupInputs {
  name: string;
  expiresAt: string;
  userFullName: string;
  password: string;
  projectLink: string;
}

@Component({
  components: {
    QuickNav,
    TopMessage,
    MeetingMembersList,
    MeetingMemberMatch,
    MeetingProjectDialog,
    ProjectIcon,
  },
  mixins: [PlatformServiceMixin],
})
export default class OnboardMeetingView extends Vue {
  $notify!: (
    notification: { group: string; type: string; title: string; text: string },
    timeout?: number,
  ) => void;
  $route!: RouteLocationNormalizedLoaded;
  $router!: Router;
  notify!: ReturnType<typeof createNotifyHelpers>;
  /** Production share domain for deep links */
  APP_SERVER = APP_SERVER;

  currentMeeting: ServerMeeting | null = null;
  newOrUpdatedMeetingInputs: MeetingSetupInputs | null = null;

  activeDid = "";
  allContacts: Contact[] = [];
  allMyDids: string[] = [];
  apiServer = "";
  isDeleting = false;
  isLoading = true;
  isLoadingMatches = false;
  isPostingMatch = false;
  isRegistered = false;
  fullName = "";
  matchPairs: MatchPair[] | null = null;
  /** Accumulated pair DIDs from every match run; sent as previousPairDids on future posts. */
  previousMatchedPairs: [string, string][] = [];

  selectedProjectData: PlanData | null = null;
  showDeleteConfirm = false;
  get minDateTime() {
    const now = new Date();
    now.setMinutes(now.getMinutes() + 5); // Set minimum 5 minutes in the future
    return this.formatDateForInput(now);
  }

  async created() {
    this.notify = createNotifyHelpers(
      this.$notify as Parameters<typeof createNotifyHelpers>[0],
    );
    const settings = await this.$accountSettings();
    this.activeDid = settings?.activeDid || "";
    this.apiServer = settings?.apiServer || "";
    this.fullName = settings?.firstName || "";
    this.isRegistered = !!settings?.isRegistered;

    // Load contacts and DIDs for dialog
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    this.allContacts = await (this as any).$contactsByDateAdded();
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    this.allMyDids = await (this as any).$getAllAccountDids();

    await this.fetchCurrentMeeting();

    // Ensure selected project is loaded if projectLink exists
    await this.ensureSelectedProjectLoaded();

    // Load pairwise matches when organizer has a meeting
    if (this.currentMeeting?.password) {
      await this.fetchMatchPairs();
    }

    this.isLoading = false;
  }

  isInCreateMode(): boolean {
    return (
      this.newOrUpdatedMeetingInputs != null && this.currentMeeting == null
    );
  }

  isInEditOrCreateMode(): boolean {
    return this.newOrUpdatedMeetingInputs != null;
  }

  getDefaultExpirationTime(): string {
    const date = new Date();
    // Round up to the next hour
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    date.setHours(date.getHours() + 1); // Round up to next hour
    date.setHours(date.getHours() + 2); // Add 2 more hours
    return this.formatDateForInput(date);
  }

  // Format a date object to YYYY-MM-DDTHH:mm format for datetime-local input
  private formatDateForInput(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    return `${year}-${month}-${day}T${hours}:${minutes}`;
  }

  blankMeeting(): MeetingSetupInputs {
    return {
      // no groupId yet
      name: "",
      expiresAt: this.getDefaultExpirationTime(),
      userFullName: this.fullName,
      password: (this.currentMeeting?.password as string) || "",
      projectLink: (this.currentMeeting?.projectLink as string) || "",
    };
  }

  async fetchCurrentMeeting() {
    try {
      const headers = await getHeaders(this.activeDid);

      const response = await this.axios.get(
        this.apiServer + "/api/partner/groupOnboard",
        { headers },
      );

      const queryPassword = this.$route.query["password"] as string;

      if (response?.data?.data) {
        this.currentMeeting = {
          ...response.data.data,
          userFullName: this.fullName,
          password: this.currentMeeting?.password || queryPassword || "",
        };
      } else {
        this.newOrUpdatedMeetingInputs = this.blankMeeting();
      }
    } catch (error: unknown) {
      this.newOrUpdatedMeetingInputs = this.blankMeeting();
    }
  }

  /**
   * Ensure the selected project is loaded if projectLink exists
   */
  async ensureSelectedProjectLoaded(): Promise<void> {
    const projectLink =
      this.currentMeeting?.projectLink ||
      this.newOrUpdatedMeetingInputs?.projectLink;

    if (!projectLink) {
      this.selectedProjectData = null;
      return;
    }

    await this.fetchProjectByHandleId(projectLink);
  }

  /**
   * Fetch a single project by handleId
   * @param handleId - The project handleId to fetch
   */
  async fetchProjectByHandleId(handleId: string): Promise<void> {
    try {
      const headers = await getHeaders(this.activeDid);
      const url = `${this.apiServer}/api/v2/report/plans?handleId=${encodeURIComponent(handleId)}`;
      const resp = await this.axios.get(url, { headers });

      if (resp.status === 200 && resp.data.data && resp.data.data.length > 0) {
        const project = resp.data.data[0];
        this.selectedProjectData = {
          name: project.name,
          description: project.description,
          image: project.image,
          handleId: project.handleId,
          issuerDid: project.issuerDid,
          rowId: project.rowId,
        };
      } else {
        this.selectedProjectData = null;
      }
    } catch (error) {
      this.$logAndConsole(
        "Error fetching project by handleId: " + errorStringForLog(error),
        true,
      );
      this.selectedProjectData = null;
    }
  }

  async createMeeting() {
    this.isLoading = true;

    try {
      if (!this.newOrUpdatedMeetingInputs) {
        throw Error(
          "There was no meeting data to create. We should never get here.",
        );
      }

      // Convert local time to UTC for comparison and server submission
      const localExpiresAt = new Date(this.newOrUpdatedMeetingInputs.expiresAt);
      const now = new Date();
      if (localExpiresAt <= now) {
        this.notify.warning(NOTIFY_MEETING_INVALID_TIME.message, TIMEOUTS.LONG);
        return;
      }
      if (!this.newOrUpdatedMeetingInputs.userFullName) {
        this.notify.warning(
          NOTIFY_MEETING_NAME_REQUIRED.message,
          TIMEOUTS.LONG,
        );
        return;
      }
      if (!this.fullName) {
        this.$saveSettings({
          firstName: this.newOrUpdatedMeetingInputs.userFullName,
        });
      }

      if (!this.newOrUpdatedMeetingInputs.password) {
        this.notify.warning(
          NOTIFY_MEETING_PASSWORD_REQUIRED.message,
          TIMEOUTS.LONG,
        );
        return;
      }
      const password: string = this.newOrUpdatedMeetingInputs.password;

      // create content with user's name & DID encrypted with password
      const content = {
        name: this.newOrUpdatedMeetingInputs.userFullName,
        did: this.activeDid,
        isRegistered: this.isRegistered,
      };
      const encryptedContent = await encryptMessage(
        JSON.stringify(content),
        password,
      );

      const headers = await getHeaders(this.activeDid);
      const response = await this.axios.post(
        this.apiServer + "/api/partner/groupOnboard",
        {
          name: this.newOrUpdatedMeetingInputs.name,
          expiresAt: localExpiresAt.toISOString(),
          content: encryptedContent,
          projectLink: this.newOrUpdatedMeetingInputs.projectLink,
        },
        { headers },
      );

      if (response.data && response.data.success) {
        this.currentMeeting = {
          ...this.newOrUpdatedMeetingInputs,
          groupId: response.data.success.groupId,
        };

        this.newOrUpdatedMeetingInputs = null;
        this.notify.success(NOTIFY_MEETING_CREATED.message, TIMEOUTS.STANDARD);
        // redirect to the same page with the password parameter set
        this.$router.push({
          name: "onboard-meeting-setup",
          query: { password: password },
        });
      } else {
        throw { response: response };
      }
    } catch (error) {
      this.$logAndConsole(
        "Error creating meeting: " + errorStringForLog(error),
        true,
      );
      const errorMessage = serverMessageForUser(error);
      this.notify.error(
        errorMessage ||
          "Failed to create meeting. Try reloading or submitting again.",
        5000,
      );
    } finally {
      this.isLoading = false;
    }
  }

  formatExpirationTime(expiresAt: string): string {
    const expiration = new Date(expiresAt); // Server time is in UTC
    const now = new Date();
    const diffHours = Math.round(
      (expiration.getTime() - now.getTime()) / (1000 * 60 * 60),
    );

    if (diffHours < 0) {
      return "Expired";
    } else if (diffHours < 1) {
      return "Less than an hour";
    } else if (diffHours === 1) {
      return "1 hour";
    } else {
      return `${diffHours} hours`;
    }
  }

  confirmDelete() {
    this.showDeleteConfirm = true;
  }

  async deleteMeeting() {
    this.isDeleting = true;
    try {
      const headers = await getHeaders(this.activeDid);
      await this.axios.delete(this.apiServer + "/api/partner/groupOnboard", {
        headers,
      });

      this.currentMeeting = null;
      this.newOrUpdatedMeetingInputs = this.blankMeeting();
      this.showDeleteConfirm = false;

      this.notify.success(NOTIFY_MEETING_DELETED.message, TIMEOUTS.STANDARD);
    } catch (error) {
      this.$logError("Error deleting meeting: " + error);
      this.notify.error(
        serverMessageForUser(error) || "Failed to delete meeting.",
        TIMEOUTS.LONG,
      );
    } finally {
      this.isDeleting = false;
    }
  }

  async startEditing() {
    // Populate form with existing meeting data
    if (this.currentMeeting) {
      const localExpiresAt = new Date(this.currentMeeting.expiresAt);
      this.newOrUpdatedMeetingInputs = {
        name: this.currentMeeting.name,
        expiresAt: this.formatDateForInput(localExpiresAt),
        userFullName: this.currentMeeting.userFullName || "",
        password: this.currentMeeting.password || "",
        projectLink: this.currentMeeting.projectLink || "",
      };
      // Ensure selected project is loaded if projectLink exists
      if (this.currentMeeting.projectLink) {
        await this.ensureSelectedProjectLoaded();
      }
    } else {
      this.$logError(
        "There is no current meeting to edit. We should never get here.",
      );
    }
  }

  async cancelEditing() {
    // Reset form data
    this.newOrUpdatedMeetingInputs = null;
    // Restore selected project from currentMeeting if it exists
    if (this.currentMeeting?.projectLink) {
      await this.ensureSelectedProjectLoaded();
    } else {
      this.selectedProjectData = null;
    }
  }

  async updateMeeting() {
    this.isLoading = true;
    if (!this.newOrUpdatedMeetingInputs) {
      throw Error("There was no meeting data to update.");
    }

    try {
      // Convert local time to UTC for comparison and server submission
      const localExpiresAt = new Date(this.newOrUpdatedMeetingInputs.expiresAt);
      const now = new Date();
      if (localExpiresAt <= now) {
        this.notify.warning(NOTIFY_MEETING_INVALID_TIME.message, TIMEOUTS.LONG);
        return;
      }
      if (!this.newOrUpdatedMeetingInputs.userFullName) {
        this.notify.warning(
          NOTIFY_MEETING_NAME_REQUIRED.message,
          TIMEOUTS.LONG,
        );
        return;
      }
      if (!this.newOrUpdatedMeetingInputs.password) {
        this.notify.warning(
          NOTIFY_MEETING_PASSWORD_REQUIRED.message,
          TIMEOUTS.LONG,
        );
        return;
      }
      // create content with user's name & DID encrypted with password
      const content = {
        name: this.newOrUpdatedMeetingInputs.userFullName,
        did: this.activeDid,
        isRegistered: this.isRegistered,
      };
      const encryptedContent = await encryptMessage(
        JSON.stringify(content),
        this.newOrUpdatedMeetingInputs.password,
      );

      const headers = await getHeaders(this.activeDid);
      const response = await this.axios.put(
        this.apiServer + "/api/partner/groupOnboard",
        {
          // the groupId is in the currentMeeting but it's not necessary while users only have one meeting
          name: this.newOrUpdatedMeetingInputs.name,
          expiresAt: localExpiresAt.toISOString(),
          content: encryptedContent,
          projectLink: this.newOrUpdatedMeetingInputs.projectLink,
        },
        { headers },
      );

      if (response.data && response.data.success) {
        // Update the current meeting with only the necessary fields
        this.currentMeeting = {
          ...this.newOrUpdatedMeetingInputs,
          groupId: (this.currentMeeting?.groupId as number) || -1,
        };
        this.newOrUpdatedMeetingInputs = null;

        if (this.currentMeeting?.password) {
          this.$router.push({
            name: "onboard-meeting-setup",
            query: { password: this.currentMeeting?.password },
          });
        }
      } else {
        throw { response: response };
      }
    } catch (error) {
      this.$logAndConsole(
        "Error updating meeting: " + errorStringForLog(error),
        true,
      );
      const errorMessage = serverMessageForUser(error);
      this.notify.error(
        errorMessage ||
          "Failed to update meeting. Try reloading or submitting again.",
        TIMEOUTS.LONG,
      );
    } finally {
      this.isLoading = false;
    }
  }

  onboardMeetingMembersLink(): string {
    if (this.currentMeeting) {
      // Use production URL for sharing to avoid localhost issues in development
      return `${APP_SERVER}/deep-link/onboard-meeting-members/${this.currentMeeting?.groupId}?password=${encodeURIComponent(
        this.currentMeeting?.password || "",
      )}`;
    }
    return "";
  }

  /**
   * Fetch current pairwise matches (GET /api/partner/groupOnboardMatch).
   * Any member of the meeting can fetch; organizer is the one who can POST.
   */
  async fetchMatchPairs(): Promise<void> {
    if (!this.currentMeeting?.password) return;
    this.isLoadingMatches = true;
    try {
      const headers = await getHeaders(this.activeDid);
      const response = await this.axios.get(
        this.apiServer + "/api/partner/groupOnboardMatch",
        { headers },
      );
      const pairs = response?.data?.data?.pairs ?? null;
      let tempMatchPairs: MatchPair[] | null = null;
      if (Array.isArray(pairs)) {
        tempMatchPairs = [];
        // walk through pairs and decrypt the content for each participant
        for (const pair of pairs) {
          for (const participant of pair.participants) {
            try {
              const decryptedContent = await decryptMessage(
                participant.content,
                this.currentMeeting?.password || "",
              );
              participant.decryptedContentObject = JSON.parse(decryptedContent);
            } catch (error) {
              this.$logAndConsole(
                "Error decrypting participant content: " +
                  errorStringForLog(error),
                true,
              );
              participant.decryptedContentObject = null;
            }
          }
          tempMatchPairs.push(pair);
        }
      }
      this.matchPairs = tempMatchPairs;
      if (tempMatchPairs?.length) {
        this.mergePairsIntoPrevious(tempMatchPairs);
      }
    } catch (error) {
      this.$logAndConsole(
        "Error fetching match pairs: " + errorStringForLog(error),
        true,
      );
      this.matchPairs = null;
      this.notify.error(
        serverMessageForUser(error as unknown as AxiosErrorResponse) ||
          "Failed to load matches.",
        TIMEOUTS.LONG,
      );
    } finally {
      this.isLoadingMatches = false;
    }
  }

  /**
   * Normalize a pair of DIDs to a sorted tuple for deduplication.
   */
  private normalizedPair(did1: string, did2: string): [string, string] {
    return did1 <= did2 ? [did1, did2] : [did2, did1];
  }

  /**
   * Append pairs from a match result into previousMatchedPairs (no duplicates).
   */
  private mergePairsIntoPrevious(pairs: MatchPair[]): void {
    for (const pair of pairs) {
      if (pair.participants?.length !== 2) continue;
      const [a, b] = pair.participants.map((p) => p.issuerDid);
      const norm = this.normalizedPair(a, b);
      const exists = this.previousMatchedPairs.some(
        ([x, y]) => x === norm[0] && y === norm[1],
      );
      if (!exists) {
        this.previousMatchedPairs.push(norm);
      }
    }
  }

  /**
   * POST to groupOnboardMatch with optional body (excludedDids, excludedPairDids, previousPairDids).
   * Organizer only; uses meeting for current user.
   */
  async postMatch(body?: {
    excludedDids?: string[];
    excludedPairDids?: [string, string][];
    previousPairDids?: [string, string][];
  }): Promise<MatchPair[] | null> {
    try {
      const headers = await getHeaders(this.activeDid);
      const response = await this.axios.post(
        this.apiServer + "/api/partner/groupOnboardMatch",
        body ?? {},
        { headers },
      );
      const pairs = response?.data?.data?.pairs ?? null;
      return Array.isArray(pairs) ? pairs : null;
    } catch (error) {
      this.$logAndConsole(
        "Error posting group onboard match: " + errorStringForLog(error),
        true,
      );
      const errorMessage = serverMessageForUser(
        error as unknown as AxiosErrorResponse,
      );
      this.notify.error(
        errorMessage || "Failed to run matching.",
        TIMEOUTS.LONG,
      );
      return null;
    }
  }

  async postNewMatchesThenRefresh(): Promise<void> {
    this.isPostingMatch = true;
    try {
      const previousPairDids = this.previousMatchedPairs.length
        ? this.previousMatchedPairs
        : undefined;
      const pairs = await this.postMatch(
        previousPairDids ? { previousPairDids } : undefined,
      );
      if (Array.isArray(pairs) && pairs.length > 0) {
        const tempMatchPairs: MatchPair[] = [];
        for (const pair of pairs) {
          for (const participant of pair.participants) {
            const decryptedContent = await decryptMessage(
              participant.content,
              this.currentMeeting?.password || "",
            );
            participant.decryptedContentObject = JSON.parse(decryptedContent);
          }
          tempMatchPairs.push(pair);
        }
        this.matchPairs = tempMatchPairs;
        this.mergePairsIntoPrevious(tempMatchPairs);
        this.notify.success("New matches generated.", TIMEOUTS.STANDARD);
      }
    } finally {
      this.isPostingMatch = false;
    }
  }

  async clearMatchesThenRefresh(): Promise<void> {
    try {
      const headers = await getHeaders(this.activeDid);
      await this.axios.delete(
        this.apiServer + "/api/partner/groupOnboardMatch",
        { headers },
      );
      this.matchPairs = null;
      this.previousMatchedPairs = [];
    } catch (error) {
      this.$logAndConsole(
        "Error clearing matches: " + errorStringForLog(error),
        true,
      );
      this.notify.error(
        serverMessageForUser(error as unknown as AxiosErrorResponse) ||
          "Failed to clear matches.",
        TIMEOUTS.LONG,
      );
    }
  }

  handleMembersError(message: string) {
    this.notify.error(message, TIMEOUTS.LONG);
  }

  async copyMembersLinkToClipboard() {
    try {
      await copyToClipboard(this.onboardMeetingMembersLink());
      this.notify.info(NOTIFY_MEETING_LINK_COPIED.message, TIMEOUTS.LONG);
    } catch (error) {
      this.$logAndConsole(
        `Error copying meeting link to clipboard: ${error}`,
        true,
      );
      this.notify.error("Failed to copy meeting link to clipboard.");
    }
  }

  /**
   * Computed property for selected project
   * Returns the separately stored selected project data
   */
  get selectedProject(): PlanData | null {
    return this.selectedProjectData;
  }

  /**
   * Computed property for selected project issuer display name
   * Uses didInfo to format the issuer name similar to ProjectCard
   */
  get selectedProjectIssuerName(): string {
    if (!this.selectedProject) {
      return "";
    }
    return didInfo(
      this.selectedProject.issuerDid,
      this.activeDid,
      this.allMyDids,
      this.allContacts,
    );
  }

  /**
   * Open the project link selection dialog
   */
  openProjectLinkDialog(): void {
    (this.$refs.meetingProjectDialog as MeetingProjectDialog).open();
  }

  /**
   * Handle project assignment from dialog
   */
  handleProjectLinkAssigned(project: PlanData): void {
    // Store the selected project directly
    this.selectedProjectData = project;

    if (this.newOrUpdatedMeetingInputs) {
      this.newOrUpdatedMeetingInputs.projectLink = project.handleId;
    }
  }

  /**
   * Unset the project link and revert to initial state
   */
  unsetProjectLink(): void {
    this.selectedProjectData = null;
    if (this.newOrUpdatedMeetingInputs) {
      this.newOrUpdatedMeetingInputs.projectLink = "";
    }
  }

  /**
   * Handle dialog open event - stop auto-refresh in MeetingMembersList
   */
  handleDialogOpen(): void {
    const membersList = this.$refs.membersList as MeetingMembersList;
    if (membersList) {
      membersList.stopAutoRefresh();
    }
  }

  /**
   * Handle dialog close event - start auto-refresh in MeetingMembersList
   */
  handleDialogClose(): void {
    const membersList = this.$refs.membersList as MeetingMembersList;
    if (membersList) {
      membersList.startAutoRefresh();
    }
  }
}
</script>
