<script setup lang="ts">
import { showAlert } from '@/alerts'
import { AnnouncementAPIClient } from '@/api/announcement'
import { useAuthStore } from '@/stores/auth'
import { type Ref, ref } from 'vue'

interface CreateAnnouncementFormData {
  type: string
  message: string
}
const createAnnouncementFormData: Ref<CreateAnnouncementFormData> = ref({ type: 'INFO', message: '' })

const authStore = useAuthStore()

async function doCreateAnnouncement() {
  const client = new AnnouncementAPIClient(authStore)
  const a = await client.createAnnouncement(
    createAnnouncementFormData.value.type, createAnnouncementFormData.value.message
  ).handleErrorsWithAlert()
  if (a !== null) {
    await showAlert('Created announcement. It will appear shortly.')
    createAnnouncementFormData.value = { type: 'INFO', message: '' }
  }
}
</script>
<template>
  <form @submit.prevent="doCreateAnnouncement">
    <h3>Create Announcement</h3>
    <div>
      <label for="create-announcement-type">Type</label>
      <select id="create-announcement-type" v-model="createAnnouncementFormData.type">
        <option value="INFO" selected>INFO</option>
        <option value="ERROR">ERROR</option>
      </select>
    </div>
    <div>
      <label for="create-announcement-message">Message</label>
      <textarea id="create-announcement-message" v-model="createAnnouncementFormData.message" maxlength="2000"
        minlength="1" required style="min-width: 300px; min-height: 100px;"></textarea>
    </div>
    <div class="button-bar">
      <button type="submit">Create</button>
    </div>
  </form>
</template>
