<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { computed, onMounted, reactive, ref } from 'vue'

import { fetchAdminListings, type Listing } from '@/api/listings'
import {
  formatMoney,
  listingBuyerPrice,
  listingDisplayTitle,
  listingSellerPrice,
  ownerName,
} from '@/views/admin/listingAdminDisplay'
import { listingReviewStatusLabel, listingStatusLabel } from '@/utils/statusLabels'
import { formatDateTime } from '@/utils/time'

const loading = ref(false)
const listings = ref<Listing[]>([])
const currentPage = ref(1)
const currentPageSize = ref(20)
const total = ref(0)
const filters = reactive({
  owner_id: '',
  status: '',
  review_status: '',
})

const publishedCount = computed(() => listings.value.filter((item) => item.status === 'published').length)
const rentedCount = computed(() => listings.value.filter((item) => item.status === 'rented').length)
const pendingCount = computed(() => listings.value.filter((item) => item.review_status === 'pending').length)

onMounted(loadListings)

async function loadListings() {
  loading.value = true
  try {
    const query = {
      ...filters,
      page: currentPage.value,
      page_size: currentPageSize.value,
    }
    const result = await fetchAdminListings(query)
    listings.value = result.items
    total.value = result.total
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  filters.owner_id = ''
  filters.status = ''
  filters.review_status = ''
  currentPage.value = 1
  void loadListings()
}

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

function statusType(status: string) {
  if (status === 'published') return 'success'
  if (status === 'rented') return 'warning'
  if (status === 'offline') return 'info'
  return ''
}

function reviewType(status: string) {
  if (status === 'approved') return 'success'
  if (status === 'pending') return 'warning'
  if (status === 'rejected') return 'danger'
  return 'info'
}
</script>

<template>
  <section class="page">
    <div class="page-header-row">
      <div class="page-header">
        <p class="eyebrow">Listings</p>
        <h1>商品管理</h1>
        <p>查看全部租号商品、号主、价格押金、上架状态和审核状态。</p>
      </div>
      <div class="toolbar-actions">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" :icon="Search" :loading="loading" @click="loadListings">查询</el-button>
      </div>
    </div>

    <div class="metric-grid">
      <div class="metric-card">
        <span>总条数</span>
        <strong>{{ total }} 个</strong>
      </div>
      <div class="metric-card">
        <span>已上架</span>
        <strong>{{ publishedCount }} 个</strong>
      </div>
      <div class="metric-card">
        <span>已锁定</span>
        <strong>{{ rentedCount }} 个</strong>
      </div>
      <div class="metric-card">
        <span>待审核</span>
        <strong>{{ pendingCount }} 个</strong>
      </div>
    </div>

    <el-form class="filter-panel" label-position="top">
      <el-form-item label="号主 ID">
        <el-input v-model="filters.owner_id" clearable placeholder="按号主筛选" />
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select v-model="filters.status" clearable placeholder="全部状态" class="full-control">
          <el-option label="草稿" value="draft" />
          <el-option label="已上架" value="published" />
          <el-option label="已锁定" value="rented" />
          <el-option label="已下架" value="offline" />
          <el-option label="异常" value="abnormal" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="filters.review_status" clearable placeholder="全部审核状态" class="full-control">
          <el-option label="未提交" value="none" />
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" class="table-panel" :data="listings">
      <el-table-column label="商品" min-width="220" fixed="left">
        <template #default="{ row }">
          <strong>{{ listingDisplayTitle(row) }}</strong>
          <span class="table-subtext">{{ row.game_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="号主" min-width="130">
        <template #default="{ row }">
          <strong>{{ ownerName(row) }}</strong>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110">
        <template #default="{ row }">
          <el-tag :type="statusType(row.status)">{{ listingStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" width="110">
        <template #default="{ row }">
          <el-tag :type="reviewType(row.review_status)">{{ listingReviewStatusLabel(row.review_status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="价格(租金/押金)" min-width="170">
        <template #default="{ row }">
          <strong>{{ listingBuyerPrice(row) }}</strong>
          <span class="table-subtext">卖家 {{ listingSellerPrice(row) }} · 押金 {{ formatMoney(row.deposit_amount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="180">
        <template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="110">
        <template #default="{ row }">
          <RouterLink :to="`/admin/listings/${row.id}`">
            <el-button size="small">详情</el-button>
          </RouterLink>
        </template>
      </el-table-column>
    </el-table>

    <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="loadListings"
        @size-change="handleSizeChange"
      />
    </div>
  </section>
</template>
