<script setup lang="ts">
import { computed, ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { Delete, Star, StarFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import ListingCard from '@/features/listings/components/ListingCard.vue'
import {
  useListingCollections,
  type ListingCollectionItem,
} from '@/features/listings/composables/useListingCollections'
import { formatCent, formatMoney } from '@/shared/utils/money'
import {
  formatHafCoinM,
  formatListingCode,
  getCoinWan,
  getListingDisplayPrice,
  getListingTitle,
} from '@/shared/utils/listingDisplay'

const route = useRoute()
const {
  history,
  favorites,
  isFavorite,
  toggleFavorite,
  removeHistory,
  removeFavorite,
  clearHistory,
} = useListingCollections()
const activeTab = ref(route.query.tab === 'favorites' ? 'favorites' : 'history')
const isMobilePage = computed(() => route.path.startsWith('/m/'))
const activeItems = computed(() =>
  activeTab.value === 'favorites' ? favorites.value : history.value
)
const emptyText = computed(() =>
  activeTab.value === 'favorites' ? '暂无收藏账号' : '暂无浏览记录'
)

async function handleClearHistory() {
  try {
    await ElMessageBox.confirm('确认清空全部浏览记录吗？', '清空确认', {
      confirmButtonText: '清空',
      cancelButtonText: '取消',
      type: 'warning',
    })
    clearHistory()
    ElMessage.success('浏览记录已清空')
  } catch {
    // 用户取消时保持原状。
  }
}

function handleToggleFavorite(item: ListingCollectionItem) {
  const added = toggleFavorite(item.listing)
  ElMessage.success(added ? '已收藏' : '已取消收藏')
}

function handleRemove(item: ListingCollectionItem) {
  if (activeTab.value === 'favorites') {
    removeFavorite(item.listing.id)
    ElMessage.success('已取消收藏')
    return
  }
  removeHistory(item.listing.id)
  ElMessage.success('已移除记录')
}

function detailPath(item: ListingCollectionItem) {
  return isMobilePage.value ? `/m/listings/${item.listing.id}` : `/listings/${item.listing.id}`
}

function timeText(item: ListingCollectionItem) {
  const value = activeTab.value === 'favorites' ? item.favorited_at : item.viewed_at
  if (!value) return ''
  return new Date(value).toLocaleString('zh-CN')
}
</script>

<template>
  <main :class="['collections-page', { mobile: isMobilePage }]">
    <header class="collections-header">
      <div>
        <p class="eyebrow">Account Memory</p>
        <h1>我的足迹</h1>
        <p>找回看过和收藏过的账号。</p>
      </div>
      <button
        v-if="activeTab === 'history' && history.length"
        type="button"
        @click="handleClearHistory"
      >
        清空记录
      </button>
    </header>

    <nav class="collection-tabs">
      <button
        :class="{ active: activeTab === 'history' }"
        type="button"
        @click="activeTab = 'history'"
      >
        浏览记录 <span>{{ history.length }}</span>
      </button>
      <button
        :class="{ active: activeTab === 'favorites' }"
        type="button"
        @click="activeTab = 'favorites'"
      >
        收藏账号 <span>{{ favorites.length }}</span>
      </button>
    </nav>

    <el-empty v-if="!activeItems.length && !isMobilePage" :description="emptyText" />
    <div v-else-if="!activeItems.length" class="mobile-empty">{{ emptyText }}</div>

    <section v-else-if="!isMobilePage" class="pc-list">
      <article v-for="item in activeItems" :key="item.listing.id" class="pc-item">
        <div class="item-meta">
          <span>{{ timeText(item) }}</span>
          <div>
            <el-button
              :icon="isFavorite(item.listing.id) ? StarFilled : Star"
              size="small"
              @click="handleToggleFavorite(item)"
            >
              {{ isFavorite(item.listing.id) ? '已收藏' : '收藏' }}
            </el-button>
            <el-button :icon="Delete" size="small" @click="handleRemove(item)">移除</el-button>
          </div>
        </div>
        <ListingCard :listing="item.listing" />
      </article>
    </section>

    <section v-else class="mobile-list">
      <article v-for="item in activeItems" :key="item.listing.id" class="mobile-card">
        <RouterLink :to="detailPath(item)" class="mobile-card-main">
          <img
            v-if="item.listing.cover_url || item.listing.screenshot_urls?.[0]"
            :src="item.listing.cover_url || item.listing.screenshot_urls?.[0]"
            :alt="getListingTitle(item.listing)"
          />
          <div v-else class="mobile-cover-empty">HFB</div>
          <div class="mobile-info">
            <strong>{{ getListingTitle(item.listing) }}</strong>
            <small>编号 {{ formatListingCode(item.listing) }}</small>
            <div class="mobile-stats">
              <span>{{ formatHafCoinM(getCoinWan(item.listing)) }}</span>
              <span>押金 ¥{{ formatCent(item.listing.deposit_amount_cent) }}</span>
            </div>
            <em>¥{{ formatMoney(getListingDisplayPrice(item.listing)) }}</em>
          </div>
        </RouterLink>
        <div class="mobile-card-actions">
          <span>{{ timeText(item) }}</span>
          <div>
            <button type="button" @click="handleToggleFavorite(item)">
              {{ isFavorite(item.listing.id) ? '已收藏' : '收藏' }}
            </button>
            <button type="button" @click="handleRemove(item)">移除</button>
          </div>
        </div>
      </article>
    </section>
  </main>
</template>

<style scoped>
.collections-page {
  display: grid;
  gap: 18px;
  padding: 24px;
}

.collections-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  padding: 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #fff7ed 0%, #ffffff 70%);
}

.eyebrow {
  margin: 0 0 6px;
  color: #ff6a00;
  font-size: 12px;
  font-weight: 800;
}

.collections-header h1 {
  margin: 0 0 8px;
  color: #101828;
}

.collections-header p {
  margin: 0;
  color: #667085;
}

.collections-header button,
.collection-tabs button,
.mobile-card-actions button {
  border: 0;
  cursor: pointer;
}

.collections-header button {
  padding: 9px 14px;
  border-radius: 999px;
  background: #fff3e8;
  color: #ff6a00;
}

.collection-tabs {
  display: inline-flex;
  width: fit-content;
  padding: 4px;
  border-radius: 999px;
  background: #f2f4f7;
}

.collection-tabs button {
  padding: 9px 18px;
  border-radius: 999px;
  background: transparent;
  color: #667085;
}

.collection-tabs button.active {
  background: #ff6a00;
  color: #fff;
}

.collection-tabs span {
  margin-left: 4px;
}

.pc-list {
  display: grid;
  gap: 14px;
}

.pc-item {
  display: grid;
  gap: 8px;
}

.item-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #98a2b3;
  font-size: 13px;
}

.collections-page.mobile {
  min-height: 100vh;
  padding: 14px;
  background: #f7f8fa;
}

.mobile .collections-header {
  padding: 16px;
}

.mobile .collections-header h1 {
  font-size: 22px;
}

.mobile .collections-header button {
  display: none;
}

.mobile .collection-tabs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  width: 100%;
  border-radius: 8px;
}

.mobile .collection-tabs button {
  border-radius: 8px;
}

.mobile-empty {
  padding: 44px 0;
  text-align: center;
  color: #98a2b3;
}

.mobile-list {
  display: grid;
  gap: 10px;
}

.mobile-card {
  overflow: hidden;
  border-radius: 8px;
  background: #fff;
}

.mobile-card-main {
  display: grid;
  grid-template-columns: 104px 1fr;
  gap: 10px;
  padding: 10px;
  color: inherit;
  text-decoration: none;
}

.mobile-card-main img,
.mobile-cover-empty {
  width: 104px;
  height: 104px;
  border-radius: 8px;
  object-fit: cover;
}

.mobile-cover-empty {
  display: grid;
  place-items: center;
  background: #f2f4f7;
  color: #cbd5e1;
  font-weight: 900;
}

.mobile-info {
  display: grid;
  align-content: start;
  gap: 6px;
  min-width: 0;
}

.mobile-info strong,
.mobile-info small {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mobile-info small,
.mobile-stats {
  color: #667085;
  font-size: 12px;
}

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

.mobile-info em {
  color: #ff6a00;
  font-style: normal;
  font-weight: 800;
}

.mobile-card-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 8px 10px 10px;
  border-top: 1px solid #f2f4f7;
  color: #98a2b3;
  font-size: 12px;
}

.mobile-card-actions div {
  display: flex;
  gap: 8px;
}

.mobile-card-actions button {
  padding: 5px 9px;
  border-radius: 999px;
  background: #fff7ed;
  color: #ff6a00;
}
</style>
