<template>
  <v-tooltip
    content-class="!tw:p-1"
    location="bottom"
    max-width="400px"
    v-model="show"
  >
    <template #activator="{ props }">
      <v-btn
        v-bind="props"
        :icon="currentState.icon"
        :color="currentState.color"
        :aria-label="serverStatusLabel"
      />
    </template>

    <v-list
      v-if="backend.socket"
      density="compact"
      flat
      :theme="theme"
      bg-color="transparent"
    >
      <v-list-item>
        <template #prepend>
          <v-icon
            v-if="backend.socket.status == 1"
            icon="mdi-checkbox-marked-circle"
            color="success"
          />
          <v-icon v-else icon="mdi-alert-circle" color="error" size="small" />
        </template>
        <v-list-item-title>
          {{ $t(`core.socket_status_${backend.socket.status || 0}`) }}
        </v-list-item-title>
      </v-list-item>
      <v-list-item>
        <template #prepend>
          <v-icon icon="mdi-update" color="info" size="small" />
        </template>
        <v-list-item-title>
          {{ $t("core.lastSocketUpdateReceivedAt") }}:<br />
          {{ lastUpdate() }}
        </v-list-item-title>
      </v-list-item>
    </v-list>
  </v-tooltip>
</template>

<script setup lang="ts">
import useStateSubscriber from "@racletteOrchestrator/composables/useStateSubscriber"
import { ref, computed } from "vue"
import { useI18n } from "vue-i18n"
import { $store } from "@racletteCore"
import { useTheme } from "vuetify"
import type { ServerState } from "@racletteCore/store/types"

const i18n = useI18n()
const show = ref(false)
const vuetifyTheme = useTheme()

const { state: backend } = useStateSubscriber<ServerState>("backend")

const theme = computed(() =>
  vuetifyTheme.global.name.value === "light" ? "dark" : "light",
)

const socketStatus = computed(
  () => backend.value?.socket?.status ?? 2,
)

const serverStatusLabel = computed(() =>
  i18n.t(`core.socket_status_${socketStatus.value || 0}`),
)

const currentState = computed(() => {
  const status = socketStatus.value

  const stateMapping = [
    { icon: "mdi-alert-circle", color: "error" }, // status 0
    { icon: "mdi-checkbox-marked-circle", color: "success" }, // status 1
    { icon: "mdi-alert-circle", color: "warning" }, // status 2 — connecting
  ]

  return stateMapping[status] ?? stateMapping[2]
})

const lastUpdate = () => {
  const projectId = $store.getState(["project", "_id"])
  const lastUpdate = localStorage.getItem(`lastUpdate_${projectId}`)

  if (!lastUpdate) {
    return
  }

  return i18n.d(new Date(lastUpdate), "long")
}
</script>
