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

  <!-- CONTENT -->
  <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">
        Individual Profile
      </h1>

      <!-- Back -->
      <a
        class="order-first text-lg text-center leading-none p-1"
        @click="$router.go(-1)"
      >
        <font-awesome icon="chevron-left" class="block text-center w-[1em]" />
      </a>

      <!-- 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>

    <!-- Loading Animation -->
    <div
      v-if="isLoading"
      class="fixed left-6 mt-16 text-center text-4xl leading-none bg-slate-400 text-white w-14 py-2.5 rounded-full"
    >
      <font-awesome icon="spinner" class="fa-spin-pulse"></font-awesome>
    </div>

    <div v-else-if="profile">
      <!-- Profile Info -->
      <div class="mt-8">
        <div class="text-sm">
          <font-awesome icon="user" class="fa-fw text-slate-400"></font-awesome>
          {{ profileDisplayName }}
          <button title="Copy Link to Profile" @click="onCopyLinkClick()">
            <font-awesome
              icon="link"
              class="text-sm text-slate-500 ml-2 mb-1"
            />
          </button>
        </div>
        <p v-if="profile.description" class="mt-4 text-slate-600">
          {{ profile.description }}
        </p>
      </div>

      <!-- Issuer Information Section -->
      <div v-if="profile" class="mt-6">
        <div
          v-if="issuerContact"
          class="bg-blue-50 border border-blue-200 rounded-lg p-4"
        >
          <h3 class="text-lg font-semibold text-blue-800 mb-2">
            <font-awesome icon="user-check" class="fa-fw mr-2" />
            Contact Information
          </h3>
          <p class="text-sm text-blue-700 mb-3">
            {{ issuerContact.name || "Contact" }} is in your contacts.
          </p>
          <div
            v-if="
              issuerContact.contactMethods &&
              issuerContact.contactMethods.length > 0
            "
            class="space-y-2"
          >
            <h4 class="font-medium text-blue-800">Contact Methods:</h4>
            <div
              v-for="method in issuerContact.contactMethods"
              :key="method.label"
              class="flex items-center text-sm"
            >
              <span class="font-medium text-blue-700 w-20"
                >{{ method.label }}:</span
              >
              <span class="text-blue-600">{{ method.value }}</span>
              <span class="text-xs text-blue-500 ml-2"
                >({{ method.type }})</span
              >
            </div>
          </div>
        </div>

        <div
          v-else
          class="bg-yellow-50 border border-yellow-200 rounded-lg p-4"
        >
          <h3 class="text-lg font-semibold text-yellow-800 mb-2">
            <font-awesome icon="user-plus" class="fa-fw mr-2" />
            Not in Contacts
          </h3>
          <p class="text-sm text-yellow-700 mb-3">
            This person has been connected but they're not in your contacts on
            this device.
          </p>
          <button
            class="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center"
            @click="toggleConnectInstructions"
          >
            <font-awesome icon="link" class="fa-fw mr-1" />
            Connect Me...
            <font-awesome
              :icon="showConnectInstructions ? 'chevron-up' : 'chevron-down'"
              class="fa-fw ml-1"
            />
          </button>

          <!-- Expandable Instructions -->
          <div
            v-if="showConnectInstructions"
            class="mt-4 p-4 bg-white border border-yellow-300 rounded-md"
          >
            <h4 class="font-medium text-gray-800 mb-3">How to Connect:</h4>

            <!-- Copy Profile Link Instructions -->
            <div class="mb-4">
              <p class="text-sm text-gray-700 mb-2">
                1. Copy a deep link to this profile and send it to someone in
                your network:
              </p>
              <button
                class="bg-blue-500 hover:bg-blue-600 text-white text-sm px-3 py-1 rounded flex items-center"
                @click="onCopyLinkClick()"
              >
                <font-awesome icon="copy" class="fa-fw mr-1" />
                Copy Profile Link
              </button>
            </div>

            <!-- Contact List -->
            <div class="mb-4">
              <p class="text-sm text-gray-700 mb-2">
                2. Send the link to one of these people:
              </p>

              <!-- Contacts from issuerDidVisibleToDids -->
              <div v-if="visibleToContacts.length > 0" class="mb-3">
                <h5 class="text-xs font-medium text-gray-600 mb-2">
                  People who can see this profile:
                </h5>
                <div class="space-y-1">
                  <div
                    v-for="contact in visibleToContacts"
                    :key="contact.did"
                    class="flex items-center text-sm bg-gray-50 p-2 rounded"
                  >
                    <font-awesome
                      icon="user"
                      class="fa-fw text-gray-500 mr-2"
                    />
                    <span class="font-medium">{{
                      contact.name || "Unnamed Contact"
                    }}</span>
                    <span class="text-xs text-gray-500 ml-2"
                      >({{ contact.did.substring(0, 20) }}...)</span
                    >
                  </div>
                </div>
              </div>

              <!-- Nearest Neighbors -->
              <div v-if="nearestNeighbors.length > 0" class="mb-3">
                <h5 class="text-xs font-medium text-gray-600 mb-2">
                  <span v-if="visibleToContacts.length > 0"
                    >Other nearby people:</span
                  >
                  <span v-else>Nearby people:</span>
                </h5>
                <div class="space-y-1">
                  <div
                    v-for="neighbor in nearestNeighbors"
                    :key="neighbor.issuerDid"
                    class="flex items-center text-sm bg-gray-50 p-2 rounded"
                  >
                    <font-awesome
                      icon="user"
                      class="fa-fw text-gray-500 mr-2"
                    />
                    <span class="font-medium">{{
                      neighborDisplayName(neighbor)
                    }}</span>
                    <span class="text-xs text-gray-500 ml-2"
                      >({{ neighbor.issuerDid.substring(0, 20) }}...)</span
                    >
                  </div>
                </div>
              </div>

              <!-- Loading state for nearest neighbors -->
              <div
                v-if="loadingNearestNeighbors"
                class="text-sm text-gray-500 flex items-center"
              >
                <font-awesome icon="spinner" class="fa-spin fa-fw mr-2" />
                Loading nearby people...
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Map for first coordinates -->
      <div v-if="hasFirstLocation" class="mt-4">
        <h2 class="text-lg font-semibold">Location</h2>
        <div class="h-96 mt-2 w-full">
          <l-map ref="profileMap" :center="firstLocationCoords" :zoom="mapZoom">
            <l-tile-layer
              :url="tileLayerUrl"
              layer-type="base"
              name="OpenStreetMap"
            />
            <l-marker :lat-lng="firstLocationCoords">
              <l-popup>{{ profileDisplayName }}</l-popup>
            </l-marker>
          </l-map>
        </div>
      </div>

      <!-- Map for second coordinates -->
      <div v-if="hasSecondLocation" class="mt-4">
        <h2 class="text-lg font-semibold">Second Location</h2>
        <div class="h-96 mt-2 w-full">
          <l-map
            ref="profileMap"
            :center="secondLocationCoords"
            :zoom="mapZoom"
          >
            <l-tile-layer
              :url="tileLayerUrl"
              layer-type="base"
              name="OpenStreetMap"
            />
            <l-marker :lat-lng="secondLocationCoords">
              <l-popup>{{ profileDisplayName }}</l-popup>
            </l-marker>
          </l-map>
        </div>
      </div>
    </div>

    <div v-else class="text-center mt-8">
      <p class="text-lg text-slate-500">Profile not found.</p>
    </div>
  </section>
</template>

<script lang="ts">
import "leaflet/dist/leaflet.css";
import { Component, Vue } from "vue-facing-decorator";
import { LMap, LTileLayer, LMarker, LPopup } from "@vue-leaflet/vue-leaflet";
import { Router, RouteLocationNormalizedLoaded } from "vue-router";

import QuickNav from "../components/QuickNav.vue";
import TopMessage from "../components/TopMessage.vue";
import {
  DEFAULT_PARTNER_API_SERVER,
  NotificationIface,
  APP_SERVER,
} from "../constants/app";
import { Contact } from "../db/tables/contacts";
import {
  didInfo,
  getHeaders,
  isHiddenDid,
  contactForDid,
} from "../libs/endorserServer";
import { UserProfile } from "../libs/partnerServer";
import { retrieveAccountDids } from "../libs/util";
import { logger } from "../utils/logger";
import { copyToClipboard } from "../services/ClipboardService";
import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
import { createNotifyHelpers, TIMEOUTS } from "@/utils/notify";
import { NOTIFY_PROFILE_LOAD_ERROR } from "@/constants/notifications";

/**
 * User Profile View Component
 *
 * Displays individual user profile information including:
 * - Basic profile data and description
 * - Location information with interactive maps
 * - Profile link sharing functionality
 *
 * Features:
 * - Profile data loading from partner API
 * - Interactive maps for location visualization
 * - Copy-to-clipboard functionality for profile links
 * - Responsive design with loading states
 *
 * @author Matthew Raymer
 */
@Component({
  components: {
    LMap,
    LMarker,
    LPopup,
    LTileLayer,
    QuickNav,
    TopMessage,
  },
  mixins: [PlatformServiceMixin],
})
export default class UserProfileView extends Vue {
  $notify!: (notification: NotificationIface, timeout?: number) => void;
  $router!: Router;
  $route!: RouteLocationNormalizedLoaded;

  notify!: ReturnType<typeof createNotifyHelpers>;

  activeDid = "";
  allContacts: Array<Contact> = [];
  allMyDids: Array<string> = [];
  isLoading = true;
  partnerApiServer = DEFAULT_PARTNER_API_SERVER;
  profile: UserProfile | null = null;
  showConnectInstructions = false;
  nearestNeighbors: Array<UserProfile> = [];
  loadingNearestNeighbors = false;

  // make this function available to the Vue template
  didInfo = didInfo;
  isHiddenDid = isHiddenDid;
  /** Production share domain for deep links */
  APP_SERVER = APP_SERVER;

  /**
   * Initializes notification helpers
   */
  created() {
    this.notify = createNotifyHelpers(this.$notify);
  }

  /**
   * Component initialization
   *
   * Loads account settings, contacts, and profile data
   * Uses PlatformServiceMixin for database operations
   */
  async mounted() {
    await this.initializeSettings();
    await this.loadContacts();
    await this.loadProfile();
  }

  /**
   * Initializes account settings from database
   */
  private async initializeSettings() {
    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.partnerApiServer = settings.partnerApiServer || this.partnerApiServer;
  }

  /**
   * Loads all contacts from database
   */
  private async loadContacts() {
    this.allContacts = await this.$getAllContacts();
    this.allMyDids = await retrieveAccountDids();
  }

  /**
   * Loads user profile data from partner API
   *
   * Handles profile loading with error handling and loading states
   */
  async loadProfile() {
    const profileId: string = this.$route.params.id as string;
    if (!profileId) {
      this.isLoading = false;
      return;
    }

    try {
      const response = await fetch(
        `${this.partnerApiServer}/api/partner/userProfile/${encodeURIComponent(profileId)}`,
        {
          method: "GET",
          headers: await getHeaders(this.activeDid),
        },
      );

      if (response.status === 200) {
        const result = await response.json();
        this.profile = result.data;
        if (this.profile && this.profile.rowId !== profileId) {
          // currently the server returns "rowid" with lowercase "i"; remove when that's fixed
          this.profile.rowId = profileId;
        }
      } else {
        throw new Error("Failed to load profile");
      }
    } catch (error) {
      logger.error("Error loading profile:", error);
      this.notify.error(NOTIFY_PROFILE_LOAD_ERROR.message, TIMEOUTS.LONG);
    } finally {
      this.isLoading = false;
    }
  }

  /**
   * Copies profile link to clipboard
   *
   * Creates a deep link to the profile and copies it to the clipboard
   * Shows success notification when completed
   */
  async onCopyLinkClick() {
    // Use production URL for sharing to avoid localhost issues in development
    const deepLink = `${APP_SERVER}/deep-link/user-profile/${this.profile?.rowId}`;
    try {
      await copyToClipboard(deepLink);
      this.notify.copied("profile link", TIMEOUTS.STANDARD);
    } catch (error) {
      this.$logAndConsole(`Error copying profile link: ${error}`, true);
      this.notify.error("Failed to copy profile link.");
    }
  }

  /**
   * Loads nearest neighbors from the partner API
   * Called when the Connect Me section is expanded
   */
  async loadNearestNeighbors() {
    if (!this.profile?.issuerDid || this.loadingNearestNeighbors) return;

    this.loadingNearestNeighbors = true;

    try {
      const response = await fetch(
        `${this.partnerApiServer}/api/partner/userProfileNearestNeighbors?issuerDid=${encodeURIComponent(this.profile.issuerDid)}`,
        {
          method: "GET",
          headers: await getHeaders(this.activeDid),
        },
      );

      if (response.status === 200) {
        const result = await response.json();
        this.nearestNeighbors = result.data || [];
      } else {
        logger.warn("Failed to load nearest neighbors:", response.status);
      }
    } catch (error) {
      logger.error("Error loading nearest neighbors:", error);
    } finally {
      this.loadingNearestNeighbors = false;
    }
  }

  /**
   * Gets display name for a neighbor profile
   * @param neighbor UserProfile object
   * @returns Display name for the neighbor
   */
  neighborDisplayName(neighbor: UserProfile) {
    return this.didInfo(
      neighbor.issuerDid,
      this.activeDid,
      this.allMyDids,
      this.allContacts,
    );
  }

  /**
   * Toggles the Connect Me instructions and loads nearest neighbors if needed
   */
  async toggleConnectInstructions() {
    this.showConnectInstructions = !this.showConnectInstructions;

    // Load nearest neighbors when expanding for the first time
    if (this.showConnectInstructions && this.nearestNeighbors.length === 0) {
      await this.loadNearestNeighbors();
    }
  }

  /**
   * Computed properties for template logic streamlining
   */

  /**
   * Gets the display name for the profile using didInfo utility
   * @returns Formatted display name for the profile owner
   */
  get profileDisplayName() {
    return this.didInfo(
      this.profile?.issuerDid,
      this.activeDid,
      this.allMyDids,
      this.allContacts,
    );
  }

  /**
   * Gets the contact information for the profile issuer
   * @returns Contact object if issuer is in contacts, undefined otherwise
   */
  get issuerContact() {
    if (!this.profile?.issuerDid) return undefined;
    return contactForDid(this.profile.issuerDid, this.allContacts);
  }

  /**
   * Gets contacts that are in the issuerDidVisibleToDids list
   * @returns Array of contacts who can see this profile
   */
  get visibleToContacts() {
    if (!this.profile?.issuerDidVisibleToDids) return [];

    return this.profile.issuerDidVisibleToDids
      .map((did) => contactForDid(did, this.allContacts))
      .filter((contact): contact is Contact => contact !== undefined);
  }

  /**
   * Checks if the profile has first location coordinates
   * @returns True if both latitude and longitude are available
   */
  get hasFirstLocation() {
    return this.profile?.locLat && this.profile?.locLon;
  }

  /**
   * Gets the coordinate array for the first location
   * @returns Array of [latitude, longitude] for map center
   */
  get firstLocationCoords() {
    return [this.profile?.locLat, this.profile?.locLon];
  }

  /**
   * Checks if the profile has second location coordinates
   * @returns True if both latitude and longitude are available
   */
  get hasSecondLocation() {
    return this.profile?.locLat2 && this.profile?.locLon2;
  }

  /**
   * Gets the coordinate array for the second location
   * @returns Array of [latitude, longitude] for map center
   */
  get secondLocationCoords() {
    return [this.profile?.locLat2, this.profile?.locLon2];
  }

  /**
   * Standard map zoom level for profile location maps
   * @returns Default zoom level for location display
   */
  get mapZoom() {
    return 12;
  }

  /**
   * OpenStreetMap tile layer URL template
   * @returns URL template for map tile fetching
   */
  get tileLayerUrl() {
    return "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
  }
}
</script>
