<template>
  <div>
    <v-card class="mb-3" title="Design" prepend-icon="mdi-pencil-ruler" :loading="loading">
      <template #text>
        <v-form class="mt-1" @submit.prevent="submit">
          <v-row dense>
            <v-col :cols="12">
              <v-textarea hide-details label="Content" density="comfortable" variant="outlined"
                          v-model="data.content" />
            </v-col>
          </v-row>

          <v-btn type="submit" class="mt-2" variant="text" prepend-icon="mdi-content-save" :disabled="loading">
            Apply Changes
          </v-btn>
        </v-form>
      </template>
    </v-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue"
import { getAtk } from "@/stores/userinfo"
import { request } from "@/scripts/request"
import { useUI } from "@/stores/ui"

const { showSnackbar, showErrorSnackbar } = useUI()
const loading = ref(false)

const data = ref<any>({})

async function read() {
  loading.value = true
  const res = await request("identity", "/api/users/me/page", {
    headers: { Authorization: `Bearer ${(await getAtk())}` }
  })
  if (res.status !== 200) {
    showErrorSnackbar(await res.text())
  } else {
    data.value = await res.json()
  }
  loading.value = false
}

async function submit() {
  const payload = data.value

  loading.value = true
  const res = await request("identity", "/api/users/me/page", {
    method: "PUT",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${await getAtk()}` },
    body: JSON.stringify(payload)
  })
  if (res.status !== 200) {
    showErrorSnackbar(await res.text())
  } else {
    await read()
    showSnackbar("Your personal page has been updated.")
  }
  loading.value = false
}

read()
</script>
