<template>
  <v-menu
    v-if="state"
    v-model="toggled"
    :close-on-click="false"
    :close-on-content-click="false"
    location="bottom"
    transition="scroll-y-transition"
    class="tw:w-[450px]"
  >
    <template #activator="{ props }">
      <v-btn v-bind="props" icon>
        <v-badge
          v-if="state.unreadCount > 0"
          dot
          :content="state.unreadCount"
          color="error"
        >
          <v-icon>mdi-bell-outline</v-icon>
        </v-badge>
        <v-icon v-else>mdi-bell-outline</v-icon>

        <v-tooltip activator="parent" location="bottom">
          {{
            $t(
              "core.receivedNotifications$count",
              state.unreadCount,
              state.unreadCount,
            )
          }}
        </v-tooltip>
      </v-btn>
    </template>

    <v-card left>
      <v-expansion-panels v-model="panel">
        <v-expansion-panel>
          <v-expansion-panel-title>{{
            $t("core.new")
          }}</v-expansion-panel-title>
          <v-expansion-panel-text>
            <v-list density="compact">
              <v-list-item
                v-for="(entry, index) in notificationQue"
                :key="index"
                @click="
                  () => {
                    /* this empty listener gives the list item a hover effect */
                  }
                "
              >
                <template #prepend>
                  <v-icon
                    v-if="entry.event === 'dataUpdate'"
                    icon="mdi-file-edit"
                  ></v-icon>
                  <v-icon
                    v-if="entry.event === 'dataCreate'"
                    icon="mdi-file-plus"
                  ></v-icon>
                  <v-icon
                    v-if="entry.event === 'dataSync'"
                    icon="mdi-folder-sync"
                  ></v-icon>
                  <v-icon
                    v-if="entry.event === 'dataDelete'"
                    icon="mdi-file-document-remove"
                  ></v-icon>
                </template>
                <v-list-item-title
                  class="tw:w-full tw:select-none"
                  :class="{
                    'tw:italic': entry.state === 'seen',
                    'tw:underline': entry.state === 'unread',
                  }"
                >
                  {{
                    entry.message.i18n
                      ? $t(entry.message.i18n, entry.message.content)
                      : $t(entry.message)
                  }}
                </v-list-item-title>
                <v-list-item-subtitle>
                  <v-row no-gutters>
                    <v-col align-self="end">
                      <UserChip
                        v-if="entry.updatedBy"
                        :user-id="entry.updatedBy"
                        compact
                      />
                      <TimeAgo
                        :timestamp="new Date(entry.time).toISOString()"
                      />
                    </v-col>
                  </v-row>
                </v-list-item-subtitle>
                <template #append>
                  <v-btn
                    v-if="entry.state === 'read'"
                    variant="text"
                    color="grey lighten-1"
                    icon="mdi-circle-small"
                    @click="markAsUnread(entry.queKey)"
                  ></v-btn>
                  <v-btn
                    v-if="entry.state === 'unread'"
                    variant="text"
                    color="grey lighten-1"
                    icon="mdi-circle-medium"
                    @click="markAsRead(entry.queKey)"
                  ></v-btn>
                  <v-btn
                    v-if="entry.state === 'seen'"
                    variant="text"
                    color="grey lighten-1"
                    icon="mdi-circle-medium"
                    @click="markAsRead(entry.queKey)"
                  ></v-btn>
                </template>
              </v-list-item>
            </v-list>
          </v-expansion-panel-text>
        </v-expansion-panel>
      </v-expansion-panels>
      <v-divider></v-divider>

      <v-card-actions>
        <v-spacer></v-spacer>

        <v-btn text @click="toggled = false"> {{ $t("core.cancel") }} </v-btn>
        <v-btn color="primary" text @click="clearAll()">
          {{ $t("core.clear") }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-menu>
</template>
<script setup lang="ts">
import { computed, ref } from "vue"
import useStateSubscriber from "@racletteOrchestrator/composables/useStateSubscriber"
import { UserChip, TimeAgo } from "@racletteOrchestrator"
import { $store } from "@racletteCore"
import { clone } from "ramda"
import type {
  Notification,
  NotificationsState,
} from "@racletteCore/store/types"

const { state } = useStateSubscriber<NotificationsState>("notifications")

const panel = ref(0)

const toggled = computed({
  get: () => state.value.toggled,
  set: (newValue) => {
    panel.value = 0

    $store.dispatch({
      type: "notifications/toggle",
      payload: {
        toggled: newValue,
      },
    })
  },
})

const notificationQue = computed<Notification[]>(() => {
  if (!state.value.items) {
    return []
  }
  const stateItems = clone(state.value.items)

  // remember our objectKey for read/unread state set in reducers
  Object.entries(stateItems).forEach(([key, value]) => {
    value.queKey = key
  })

  return Object.values(stateItems).sort(
    (a, b) => new Date(b.time) - new Date(a.time),
  )
})

const clearAll = () => {
  $store.dispatch({
    type: "notifications/clear",
  })
  toggled.value = false
}

const markAsRead = (queKey) =>
  $store.dispatch({
    type: "notifications/markAsRead",
    payload: {
      queKey,
    },
  })

const markAsUnread = (queKey) =>
  $store.dispatch({
    type: "notifications/markUnread",
    payload: {
      queKey,
    },
  })
</script>
