<template>
  <v-app-bar :order="5" color="grey-lighten-3">
    <div class="max-md:px-5 md:px-12 flex flex-grow-1 items-center">
      <v-app-bar-nav-icon icon="mdi-chat" :loading="loading" />

      <h2 class="ml-2 text-lg font-500">{{ channels.current?.name }}</h2>
      <p class="ml-3 text-xs opacity-80">{{ channels.current?.description }}</p>

      <v-spacer />

      <div v-if="channels.current">
        <channel-action :item="channels.current" />
      </div>
    </div>
  </v-app-bar>

  <router-view />

  <!-- @vue-ignore -->
  <v-snackbar v-model="error" :timeout="5000">Something went wrong... {{ error }}</v-snackbar>
</template>

<script setup lang="ts">
import { request } from "@/scripts/request"
import { useRoute } from "vue-router"
import { ref, watch } from "vue"
import { useChannels } from "@/stores/channels"
import ChannelAction from "@/components/chat/channels/ChannelAction.vue"

const route = useRoute()
const channels = useChannels()

const error = ref<string | null>(null)
const loading = ref(false)

async function readMetadata() {
  loading.value = true
  const res = await request("messaging", `/api/channels/${route.params.channel}`)
  if (res.status !== 200) {
    error.value = await res.text()
  } else {
    error.value = null
    channels.current = await res.json()
  }
  loading.value = false
}

watch(
  () => route.params.channel,
  () => {
    channels.messages = []
    readMetadata()
  },
  { immediate: true }
)

watch(() => channels.done, (val) => {
  if (val) {
    readMetadata().then(() => {
      channels.messages = []
      channels.done = false
    })
  }
}, { immediate: true })
</script>