<script setup lang="ts">
import { request, unwrapApiBody, type ApiResponse } from '../../../utils/http/factory'

definePageMeta({ title: '时光机' })

type Ev = { id: number; title: string; occurredOn: string; visibility: string }

const events = ref<Ev[]>([])
const loading = ref(true)

const form = reactive({
  occurredOn: new Date().toISOString().slice(0, 10),
  title: '',
  bodyMarkdown: '',
  linkUrl: '',
  visibility: 'private',
})

async function load() {
  loading.value = true
  try {
    const res = await request<ApiResponse<{ events: Ev[] }>>('/api/me/timeline')
    events.value = unwrapApiBody(res).events
  } finally {
    loading.value = false
  }
}

onMounted(load)

async function add() {
  await request('/api/me/timeline', {
    method: 'POST',
    body: {
      occurredOn: new Date(form.occurredOn).toISOString(),
      title: form.title,
      bodyMarkdown: form.bodyMarkdown || null,
      linkUrl: form.linkUrl || null,
      visibility: form.visibility,
    },
  })
  form.title = ''
  form.bodyMarkdown = ''
  form.linkUrl = ''
  await load()
}
</script>

<template>
  <UContainer class="py-8 space-y-8 max-w-3xl">
    <h1 class="text-2xl font-semibold">
      时光机
    </h1>

    <UCard>
      <template #header>
        新建事件
      </template>
      <div class="space-y-3">
        <UInput v-model="form.occurredOn" type="date" />
        <UInput v-model="form.title" placeholder="标题" />
        <UInput v-model="form.linkUrl" placeholder="链接（可选）" />
        <UTextarea v-model="form.bodyMarkdown" placeholder="正文（可选）" :rows="4" class="w-full" />
        <USelect
          v-model="form.visibility"
          :items="[
            { label: '私密', value: 'private' },
            { label: '公开', value: 'public' },
            { label: '仅链接', value: 'unlisted' },
          ]"
        />
        <UButton @click="add">
          添加
        </UButton>
      </div>
    </UCard>

    <div v-if="loading" class="text-muted">
      加载中…
    </div>
    <ul v-else class="space-y-2">
      <li v-for="e in events" :key="e.id" class="border border-default rounded-lg p-3 text-sm">
        <div class="font-medium">
          {{ e.title }}
        </div>
        <div class="text-muted">
          {{ e.occurredOn }} · {{ e.visibility }}
        </div>
      </li>
    </ul>
  </UContainer>
</template>
