<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

import { fetchNotifications, markNotificationRead, type NotificationItem } from '@/features/auth/api/notifications'
import { formatDateTime } from '@/utils/time'

const loading = ref(false)
const notifications = ref<NotificationItem[]>([])
const currentPage = ref(1)
const currentPageSize = ref(20)
const total = ref(0)

onMounted(loadNotifications)

async function loadNotifications() {
  loading.value = true
  try {
    const result = await fetchNotifications(currentPage.value, currentPageSize.value)
    notifications.value = result.items
    total.value = result.total
  } finally {
    loading.value = false
  }
}

function handleSizeChange() {
  currentPage.value = 1
  loadNotifications()
}

async function markRead(id: number) {
  await markNotificationRead(id)
  ElMessage.success('已标记为已读')
  await loadNotifications()
}
</script>

<template>
  <section class="page">
    <div class="page-header">
      <p class="eyebrow">Notifications</p>
      <h1>站内信</h1>
      <p>接收审核、交接、归还、申诉和仲裁结果通知。</p>
    </div>

    <el-empty v-if="!loading && notifications.length === 0" description="暂无站内信" />
    <div v-else v-loading="loading" class="notification-list">
      <div v-for="item in notifications" :key="item.id" class="notification-item" :class="{ unread: !item.read_at }">
        <div>
          <span>{{ item.type }}</span>
          <h2>{{ item.title }}</h2>
          <p>{{ item.content }}</p>
          <small>{{ formatDateTime(item.created_at) }}</small>
        </div>
        <div class="notification-actions">
          <RouterLink v-if="item.biz_type === 'order' && item.biz_id" :to="`/orders/${item.biz_id}`">
            <el-button size="small">查看订单</el-button>
          </RouterLink>
          <el-button v-if="!item.read_at" size="small" type="primary" @click="markRead(item.id)">已读</el-button>
        </div>
      </div>
    </div>

    <div class="pagination-wrap" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="currentPageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @current-change="loadNotifications"
        @size-change="handleSizeChange"
      />
    </div>
  </section>
</template>
