<script setup lang="ts">
import LogbookMessage from '@/components/LogbookMessage.vue'
import NoteText from '@/components/NoteText.vue'
import { onMounted, ref, type Ref } from 'vue'

const LOGBOOK_URL = 'https://logbook.andrewlalis.com'

export interface Message {
  createdAt: string
  name: string
  message: string
}

const messages: Ref<Message[]> = ref([])
const addingMessage = ref(false)
const messageSubmitted = ref(false)
const formName = ref('')
const formMessage = ref('')

onMounted(async () => {
  messages.value = await getMessages()
})

async function getMessages(): Promise<Message[]> {
  try {
    const response = await fetch(LOGBOOK_URL)
    if (response.ok) {
      return (await response.json()) as Message[]
    } else {
      console.warn('Failed to get logbook messages.', response.status)
    }
  } catch (error) {
    console.error('Failed to send logbook request.', error)
  }
  return [] // In case of error, always return an empty list.
}

async function submitMessage() {
  const data = {
    name: formName.value,
    message: formMessage.value
  }
  try {
    const response = await fetch(LOGBOOK_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      },
      body: JSON.stringify(data)
    })
    if (response.ok) {
      messages.value = await getMessages()
      formName.value = ''
      formMessage.value = ''
      addingMessage.value = false
      messageSubmitted.value = true
    } else {
      console.warn('Log message rejected.', response.status)
    }
  } catch (error) {
    console.error('Failed to send log message.', error)
  }
}
</script>
<template>
  <main>
    <p>
      If you'd like, you can leave a message in my online logbook so that I and others might see it.
      <a
        href="#"
        v-if="!messageSubmitted"
        @click.prevent="addingMessage = !addingMessage"
        class="button-link"
        >Add your message.</a
      >
    </p>
    <form v-if="addingMessage" class="message-form">
      <div class="form-row">
        <label for="nameField">Name</label>
        <input
          id="nameField"
          class="message-form-input"
          type="text"
          name="name"
          minlength="2"
          maxlength="32"
          required
          v-model="formName"
        />
      </div>
      <div class="form-row">
        <label for="messageField">Message</label>
        <textarea
          id="messageField"
          class="message-form-input"
          type="text"
          name="message"
          minlength="2"
          maxlength="255"
          required
          v-model="formMessage"
        ></textarea>
      </div>
      <div class="form-row">
        <a href="#" @click.prevent="submitMessage()" class="button-link">Submit your message!</a>
      </div>
      <NoteText>
        Note that I do check all logs and some basic information about who sent them (IP address,
        browser, etc). Inappropriate comments will be removed and their authors banned.
      </NoteText>
    </form>

    <TransitionGroup name="messages" tag="div">
      <LogbookMessage v-for="msg in messages" :key="msg.createdAt" :message="msg" />
    </TransitionGroup>
  </main>
</template>
<style>
.button-link {
  color: var(--success-color);
  text-decoration: none;
}
.button-link:hover {
  text-decoration: underline;
}
.message-form {
  margin-bottom: 1rem;
  padding-left: 1rem;
  padding-right: 1rem;
}
.form-row {
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}
.form-row > label {
  display: block;
  font-weight: bold;
  margin-bottom: 0.25rem;
}
.message-form-input {
  font-family: OpenSans;
  font-size: 16px;
}
#messageField {
  width: 100%;
}

.messages-enter-active,
.messages-leave-active {
  transition: all 0.5s ease;
}

.messages-enter-from,
.messages-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>
