<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useWithdrawStore } from '@/stores/withdraw'
import { useToast } from '@/composables/useToast'

const { t } = useI18n()
const router = useRouter()
const store = useWithdrawStore()
const { records, recordLoading, recordHasMore } = storeToRefs(store)
const toast = useToast()

function goBack() {
  router.back()
}

const STATUS_CLASS: Record<string, string> = {
  '0': 'pending',
  '1': 'processing',
  '2': 'failed',
  '3': 'success',
  '4': 'cancelled',
}

function statusText(status: string) {
  switch (status) {
    case '0':
      return t('withdraw.statusPending')
    case '1':
      return t('withdraw.statusReleasing')
    case '2':
      return t('withdraw.statusWithdrawFailed')
    case '3':
      return t('withdraw.statusWithdrawSuccess')
    case '4':
      return t('withdraw.statusWithdrawCancelled')
    default:
      return status
  }
}

onMounted(() =>
  store.loadRecords(true).catch((e: Error) => toast.error(e?.message ?? t('common.loadFailed'))),
)

async function cancel(r: (typeof records.value)[0]) {
  if (!confirm(t('withdraw.confirmCancelApply'))) {
    return
  }
  try {
    await store.cancelRecord(r.id, r.isTransfer)
    toast.success(t('withdraw.withdrawCancelledToast'))
  } catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : t('withdraw.withdrawCancelFailedToast'))
  }
}

function goDetail(r: (typeof records.value)[0]) {
  router.push({ path: `/assets/withdraw/${r.id}`, query: { isTransfer: r.isTransfer ? '1' : '0' } })
}

/** 列表金额：与 App 一致，无有效数量时显示占位符 */
function rowAmountText(r: (typeof records.value)[0]) {
  const v = (r.isTransfer ? r.transferAmount : r.amount)?.trim()
  if (!v) {
    return '--'
  }
  return `-${v}`
}
</script>

<template>
  <main class="page-main">
    <div class="page-container content">
      <div class="page-header">
        <button type="button" class="back-link" @click="goBack">{{ t('deposit.backWithArrow') }}</button>
        <h1 class="page-title">{{ t('withdraw.recordTitle') }}</h1>
      </div>

      <div v-if="recordLoading && !records.length" class="loading-state"><div class="spinner" /></div>

      <template v-else>
        <div v-if="!records.length" class="empty dark-card"><p>{{ t('withdraw.recordEmpty') }}</p></div>

        <div v-else class="list dark-card">
          <div
            v-for="r in records"
            :key="`${r.id}-${r.isTransfer}`"
            class="record-row"
            @click="goDetail(r)"
          >
            <div class="rec-left">
              <p class="rec-coin">
                {{ r.coin?.aliasName || r.coin?.coinName || 'USDT' }}
                <span class="badge-type">{{
                  r.isTransfer ? t('withdraw.typeInternalTransfer') : t('withdraw.typeOnChainWithdraw')
                }}</span>
              </p>
              <p class="rec-addr">{{ r.address?.slice(0, 12) }}{{ r.address?.length > 12 ? '…' : '' }}</p>
              <p class="rec-time">{{ r.createTime }}</p>
            </div>
            <div class="rec-right">
              <p class="rec-amount">{{ rowAmountText(r) }}</p>
              <span class="status-badge" :class="STATUS_CLASS[r.status] ?? 'pending'">{{
                statusText(r.status)
              }}</span>
              <button
                v-if="r.status === '0'"
                type="button"
                class="cancel-btn"
                @click.stop="cancel(r)"
              >
                {{ t('withdraw.cancelApplyBtn') }}
              </button>
            </div>
          </div>
        </div>

        <div class="load-more-wrap">
          <button
            v-if="recordHasMore"
            type="button"
            class="load-more-btn"
            :disabled="recordLoading"
            @click="store.loadRecords()"
          >
            {{ recordLoading ? t('common.loading') : t('deposit.histLoadMore') }}
          </button>
          <p v-else-if="records.length" class="no-more">{{ t('deposit.histLoadedAll') }}</p>
        </div>
      </template>
    </div>
  </main>
</template>

<style scoped>
.content { padding-top: var(--space-8); padding-bottom: var(--space-16); max-width: 700px; }
.page-header { margin-bottom: var(--space-8); }
.back-link {
  font-family: inherit;
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  display: inline-block;
  margin-bottom: var(--space-3);
  padding: 0;
  background: none;
  border: none;
  cursor: pointer;
  text-align: left;
}
.back-link:hover { color: var(--color-primary); }
.page-title { font-size: var(--text-h1); font-weight: var(--fw-bold); color: var(--color-text-primary); }
.loading-state { display: flex; justify-content: center; padding: var(--space-16); }
.spinner { width: 32px; height: 32px; border-radius: 50%; border: 2px solid var(--color-border); border-top-color: var(--color-primary); animation: spin .8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.empty { padding: var(--space-12); text-align: center; color: var(--color-text-muted); }
.list { overflow: hidden; }
.record-row { display: flex; justify-content: space-between; align-items: flex-start; padding: var(--space-4) var(--space-6); border-bottom: 1px solid var(--color-border); cursor: pointer; transition: background var(--transition); }
.record-row:last-child { border-bottom: none; }
.record-row:hover { background: var(--color-bg-card-hover); }
.rec-coin { font-size: var(--text-small); font-weight: var(--fw-semibold); color: var(--color-text-primary); display: flex; align-items: center; gap: var(--space-2); margin-bottom: 2px; }
.badge-type { font-size: var(--text-caption); color: var(--color-text-muted); background: var(--color-bg-card); padding: 1px 6px; border-radius: var(--radius-sm); }
.rec-addr { font-size: var(--text-caption); color: var(--color-text-muted); font-family: var(--font-family-num); }
.rec-time { font-size: var(--text-caption); color: var(--color-text-muted); margin-top: 2px; }
.rec-right { text-align: right; display: flex; flex-direction: column; align-items: flex-end; gap: var(--space-1); }
.rec-amount { font-size: var(--text-body); font-weight: var(--fw-semibold); color: var(--color-text-primary); font-family: var(--font-family-num); }
.status-badge { font-size: var(--text-caption); font-weight: var(--fw-semibold); padding: 2px 8px; border-radius: var(--radius-sm); }
.status-badge.pending     { color: #F0B90B; background: rgba(240,185,11,.1); }
.status-badge.processing  { color: #1890ff; background: rgba(24,144,255,.1); }
.status-badge.success     { color: var(--color-up); background: rgba(0,208,132,.1); }
.status-badge.failed      { color: var(--color-down); background: rgba(246,70,93,.1); }
.status-badge.cancelled   { color: var(--color-text-muted); background: var(--color-bg-card); }
.cancel-btn { background: transparent; border: 1px solid var(--color-down); border-radius: var(--radius-sm); color: var(--color-down); font-size: var(--text-caption); padding: 2px 8px; cursor: pointer; }
.load-more-wrap { text-align: center; margin-top: var(--space-5); }
.load-more-btn { background: transparent; border: 1px solid var(--color-border); border-radius: var(--radius-md); color: var(--color-text-secondary); padding: var(--space-3) var(--space-8); cursor: pointer; }
.load-more-btn:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
.load-more-btn:disabled { opacity: .5; cursor: not-allowed; }
.no-more { font-size: var(--text-caption); color: var(--color-text-muted); }
</style>
