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

import { fetchSellerListings, offlineListing, submitListingReview, type Listing } from '@/api/listings'

const loading = ref(false)
const listings = ref<Listing[]>([])

onMounted(loadListings)

async function loadListings() {
  loading.value = true
  try {
    listings.value = await fetchSellerListings()
  } finally {
    loading.value = false
  }
}

async function submitReview(id: number) {
  await submitListingReview(id)
  ElMessage.success('已提交审核，等待后台处理')
  await loadListings()
}

async function offline(id: number) {
  await offlineListing(id)
  ElMessage.success('已下架')
  await loadListings()
}
</script>

<template>
  <section class="page">
    <div class="page-header page-header-row">
      <div>
        <p class="eyebrow">Seller</p>
        <h1>我的发布</h1>
        <p>管理账号发布、审核状态、上架和下架。</p>
      </div>
      <RouterLink to="/seller/listings/create">
        <el-button type="primary">发布账号</el-button>
      </RouterLink>
    </div>

    <el-table v-loading="loading" class="table-panel" :data="listings">
      <el-table-column prop="title" label="标题" min-width="180" />
      <el-table-column prop="server_region" label="区服" width="120" />
      <el-table-column prop="haf_coin_amount" label="哈夫币" width="120" />
      <el-table-column prop="price_hourly" label="时租" width="100" />
      <el-table-column prop="deposit_amount" label="押金" width="100" />
      <el-table-column prop="status" label="状态" width="110" />
      <el-table-column prop="review_status" label="审核" width="110" />
      <el-table-column prop="review_reason" label="审核原因" min-width="160" show-overflow-tooltip />
      <el-table-column label="操作" width="190">
        <template #default="{ row }">
          <el-button size="small" :disabled="row.review_status === 'pending' || row.status === 'rented'" @click="submitReview(row.id)">
            提审
          </el-button>
          <el-button size="small" type="danger" :disabled="row.status === 'rented'" @click="offline(row.id)">下架</el-button>
        </template>
      </el-table-column>
    </el-table>
  </section>
</template>
