<script setup lang="ts">
import { CopyDocument, Edit, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import {
  fetchSellerListings,
  offlineListing,
  submitListingReview,
  type Listing,
} from '@/features/listings'
import { formatCent, formatMoneyWithSymbol } from '@/shared/utils/money'
import { listingReviewStatusLabel, listingStatusLabel } from '@/shared/utils/statusLabels'
import { formatListingCode, getListingSellerPrice } from '@/shared/utils/listingDisplay'

const loading = ref(false)
const submittingID = ref<number | null>(null)
const offliningID = ref<number | null>(null)
const listings = ref<Listing[]>([])
const statusFilter = ref('all')
const route = useRoute()

const displayListings = computed(() => {
  if (statusFilter.value === 'all') return listings.value
  if (statusFilter.value === 'pending') return listings.value.filter(item => isPendingReview(item))
  return listings.value.filter(item => item.status === statusFilter.value)
})

const stats = computed(() => [
  { key: 'all', label: '全部发布', value: listings.value.length },
  {
    key: 'published',
    label: '已上架',
    value: listings.value.filter(item => item.status === 'published').length,
  },
  {
    key: 'pending',
    label: '待审核',
    value: listings.value.filter(item => isPendingReview(item)).length,
  },
  {
    key: 'offline',
    label: '已下架',
    value: listings.value.filter(item => item.status === 'offline').length,
  },
  {
    key: 'completed',
    label: '已完成',
    value: listings.value.filter(item => item.status === 'completed').length,
  },
])

onMounted(loadListings)

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

async function submitReview(row: Listing) {
  submittingID.value = row.id
  try {
    const listing = await submitListingReview(row.id)
    replaceListing(listing)
    ElMessage.success(
      listing.status === 'published' && listing.review_status === 'approved'
        ? '已上架'
        : '已提交审核，等待后台处理'
    )
  } finally {
    submittingID.value = null
  }
}

async function offline(row: Listing) {
  try {
    await ElMessageBox.confirm(
      `确认下架「${row.title}」吗？下架后后台待审列表会同步移除。`,
      '下架确认',
      {
        confirmButtonText: '确认下架',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
  } catch {
    return
  }
  offliningID.value = row.id
  try {
    const listing = await offlineListing(row.id)
    replaceListing(listing)
    ElMessage.success('已下架')
  } finally {
    offliningID.value = null
  }
}

function replaceListing(next: Listing) {
  const index = listings.value.findIndex(item => item.id === next.id)
  if (index >= 0) {
    listings.value.splice(index, 1, next)
  } else {
    listings.value.unshift(next)
  }
}

function listingPrice(row: Listing) {
  return formatMoneyWithSymbol(getListingSellerPrice(row))
}

async function copyListingCode(row: Listing) {
  try {
    await navigator.clipboard.writeText(formatListingCode(row))
    ElMessage.success('商品编号已复制')
  } catch {
    ElMessage.error('复制失败')
  }
}

function coinText(row: Listing) {
  const coinM = Number(row.haf_coin_amount || 0) / 1000000
  return Number.isInteger(coinM) ? `${coinM}M` : `${coinM.toFixed(2)}M`
}

function canSubmit(row: Listing) {
  return !isTerminalListing(row) && !isPendingReview(row) && row.status !== 'published'
}

function canEdit(row: Listing) {
  return !isTerminalListing(row) && !isPendingReview(row) && row.status !== 'published'
}

function canOffline(row: Listing) {
  return !isTerminalListing(row) && row.status !== 'offline'
}

function editPath(row: Listing) {
  return route.path.startsWith('/m/')
    ? `/m/seller/listings/${row.id}/edit`
    : `/seller/listings/${row.id}/edit`
}

function statusTone(status: string) {
  const tones: Record<string, string> = {
    published: 'success',
    draft: 'info',
    offline: 'muted',
    completed: 'success',
    sealed: 'danger',
    rented: 'warning',
    abnormal: 'danger',
  }
  return tones[status] || 'info'
}

function reviewTone(status: string) {
  const tones: Record<string, string> = {
    approved: 'success',
    pending: 'warning',
    rejected: 'danger',
    none: 'muted',
  }
  return tones[status] || 'info'
}

function effectiveReviewStatus(row: Listing) {
  return row.status === 'offline' ? 'none' : row.review_status
}

function showReviewStatus(row: Listing) {
  return row.status !== 'completed'
}

function isTerminalListing(row: Listing) {
  return row.status === 'rented' || row.status === 'completed' || row.status === 'sealed'
}

function isPendingReview(row: Listing) {
  return !isTerminalListing(row) && row.status !== 'offline' && row.review_status === 'pending'
}
</script>

<template>
  <section class="page seller-listings-page">
    <div class="seller-hero">
      <div class="hero-text">
        <h1>我的商品</h1>
        <p>查看账号状态、审核进度，并管理上架与下架。</p>
      </div>
      <div class="hero-actions">
        <el-button :icon="Refresh" :loading="loading" @click="loadListings">刷新</el-button>
        <RouterLink to="/seller/listings/create">
          <el-button type="primary" :icon="Plus">发布账号</el-button>
        </RouterLink>
      </div>
    </div>

    <div class="seller-stats">
      <button
        v-for="item in stats"
        :key="item.key"
        type="button"
        class="stat-chip"
        :class="{ active: statusFilter === item.key }"
        @click="statusFilter = item.key"
      >
        {{ item.label }}
        <strong>{{ item.value }}</strong>
      </button>
    </div>

    <div v-loading="loading" class="listing-card-panel">
      <el-empty v-if="!displayListings.length" description="暂无符合条件的发布" />

      <article v-for="item in displayListings" :key="item.id" class="listing-card">
        <div class="listing-card-head">
          <button class="listing-code-chip" type="button" @click="copyListingCode(item)">
            编号 {{ formatListingCode(item) }}
            <el-icon><CopyDocument /></el-icon>
          </button>
          <div class="listing-tags">
            <span class="status-pill" :class="statusTone(item.status)">{{
              listingStatusLabel(item.status)
            }}</span>
            <span
              v-if="showReviewStatus(item)"
              class="status-pill"
              :class="reviewTone(effectiveReviewStatus(item))"
            >
              {{ listingReviewStatusLabel(effectiveReviewStatus(item)) }}
            </span>
          </div>
        </div>

        <h3 class="listing-title">{{ item.title }}</h3>

        <div class="listing-meta-grid">
          <div>
            <span>区服</span>
            <strong>{{ item.server_region || '-' }}</strong>
          </div>
          <div>
            <span>哈夫币</span>
            <strong>{{ coinText(item) }}</strong>
          </div>
          <div>
            <span>价格</span>
            <strong class="price-text">{{ listingPrice(item) }}</strong>
          </div>
          <div>
            <span>押金</span>
            <strong>¥{{ formatCent(item.deposit_amount_cent) }}</strong>
          </div>
        </div>

        <p v-if="item.review_reason" class="review-reason">{{ item.review_reason }}</p>

        <div class="listing-actions">
          <RouterLink v-if="canEdit(item)" :to="editPath(item)">
            <el-button :icon="Edit">编辑</el-button>
          </RouterLink>
          <el-button
            :disabled="!canSubmit(item)"
            :loading="submittingID === item.id"
            @click="submitReview(item)"
          >
            提审
          </el-button>
          <el-button
            type="danger"
            plain
            :disabled="!canOffline(item)"
            :loading="offliningID === item.id"
            @click="offline(item)"
          >
            下架
          </el-button>
        </div>
      </article>
    </div>
  </section>
</template>

<style scoped>
.seller-listings-page {
  display: grid;
  gap: 16px;
}

.seller-hero {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  padding: 18px 22px;
  border: 1px solid #eef1f6;
  border-radius: 14px;
  background: #fff;
}

.hero-text h1 {
  margin: 0;
  color: #0f172a;
  font-size: 22px;
  font-weight: 800;
}

.hero-text p {
  margin: 6px 0 0;
  color: #94a3b8;
  font-size: 13px;
}

.hero-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: flex-end;
}

.seller-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.stat-chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 7px 14px;
  border: 1px solid #e6ebf2;
  border-radius: 999px;
  background: #fff;
  color: #64748b;
  font-size: 13px;
  font-weight: 700;
  cursor: pointer;
  transition:
    border-color 0.15s ease,
    color 0.15s ease,
    background 0.15s ease;
}

.stat-chip strong {
  color: #0f172a;
  font-size: 13px;
}

.stat-chip:hover {
  border-color: #cdddf5;
}

.stat-chip.active {
  border-color: #409eff;
  background: #ecf5ff;
  color: #1d6fd0;
}

.stat-chip.active strong {
  color: #1d6fd0;
}

.listing-card-panel {
  min-height: 220px;
}

.listing-card-panel:not(:has(.el-empty)) {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 14px;
  align-content: start;
}

.listing-card {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px 18px;
  border: 1px solid #eef1f6;
  border-radius: 12px;
  background: #fff;
  transition:
    border-color 0.15s ease,
    box-shadow 0.15s ease;
}

.listing-card:hover {
  border-color: #d7e3f4;
  box-shadow: 0 6px 20px rgba(15, 23, 42, 0.06);
}

.listing-card-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.listing-code-chip {
  display: inline-flex;
  flex-shrink: 0;
  align-items: center;
  gap: 5px;
  padding: 3px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: #f8fafc;
  color: #64748b;
  font-size: 12px;
  font-weight: 700;
  cursor: pointer;
}

.listing-code-chip:hover {
  border-color: #cbd5e1;
  color: #475569;
}

.listing-title {
  min-width: 0;
  margin: 0;
  overflow: hidden;
  color: #1f2937;
  font-size: 16px;
  font-weight: 700;
  line-height: 1.45;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.listing-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  justify-content: flex-end;
}

.status-pill {
  display: inline-flex;
  align-items: center;
  min-height: 22px;
  padding: 0 9px;
  border-radius: 6px;
  background: #f1f5f9;
  color: #64748b;
  font-size: 12px;
  font-weight: 700;
}

.status-pill.success {
  background: #ecfdf3;
  color: #15803d;
}

.status-pill.warning {
  background: #fff7ed;
  color: #c2410c;
}

.status-pill.danger {
  background: #fef2f2;
  color: #dc2626;
}

.status-pill.info {
  background: #eff6ff;
  color: #2563eb;
}

.status-pill.muted {
  background: #f1f5f9;
  color: #64748b;
}

.listing-meta-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px 18px;
  padding: 12px 14px;
  border-radius: 10px;
  background: #f8fafc;
}

.listing-meta-grid div {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 8px;
}

.listing-meta-grid span {
  color: #94a3b8;
  font-size: 12px;
  font-weight: 600;
}

.listing-meta-grid strong {
  color: #334155;
  font-size: 14px;
  font-weight: 700;
}

.price-text {
  color: #f97316 !important;
  font-size: 15px !important;
}

.review-reason {
  margin: 0;
  padding: 9px 12px;
  border-radius: 8px;
  background: #fff7ed;
  color: #b45309;
  font-size: 13px;
  font-weight: 600;
  line-height: 1.6;
}

.listing-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: auto;
  padding-top: 12px;
  border-top: 1px solid #f1f5f9;
}

@media (max-width: 768px) {
  .seller-hero {
    flex-direction: column;
    align-items: stretch;
  }

  .hero-actions {
    justify-content: stretch;
  }
}
</style>
