<template>
  <v-card title="Establish a channel" prepend-icon="mdi-pound-box" class="min-h-[540px]" :loading="loading">
    <v-form @submit.prevent="submit">
      <v-card-text>
        <v-text-field label="Alias" variant="outlined" density="comfortable" hint="Must be unique"
                      v-model="data.alias" />
        <v-text-field label="Name" variant="outlined" density="comfortable" v-model="data.name" />
        <v-textarea label="Description" variant="outlined" density="comfortable" v-model="data.description" />
      </v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>

        <v-btn type="reset" color="grey-darken-3" @click="channels.show.editor = false">Cancel</v-btn>
        <v-btn type="submit" :disabled="loading">Save</v-btn>
      </v-card-actions>
    </v-form>
  </v-card>

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

<script setup lang="ts">
import { ref, watch } from "vue"
import { getAtk } from "@/stores/userinfo"
import { request } from "@/scripts/request"
import { useChannels } from "@/stores/channels"

const emits = defineEmits(["relist"])

const channels = useChannels()

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

const data = ref({
  alias: "",
  name: "",
  description: ""
})

async function submit(evt: SubmitEvent) {
  const form = evt.target as HTMLFormElement
  const payload = data.value
  if (!payload.name) return

  const url = channels.related.edit_to ? `/api/channels/${channels.related.edit_to?.id}` : "/api/channels"
  const method = channels.related.edit_to ? "PUT" : "POST"

  loading.value = true
  const res = await request("messaging", url, {
    method: method,
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${await getAtk()}` },
    body: JSON.stringify(payload)
  })
  if (res.status !== 200) {
    error.value = await res.text()
  } else {
    emits("relist")
    form.reset()
    channels.done = true
    channels.show.editor = false
    channels.related.edit_to = null
  }
  loading.value = false
}

watch(
  channels.related,
  (val) => {
    if (val.edit_to) {
      data.value = JSON.parse(JSON.stringify(val.edit_to))
    }
  },
  { immediate: true }
)
</script>
