<script setup lang="ts">
import { onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useStatementStore, type AssetStatement } from '@/stores/statement'
import { useToast } from '@/composables/useToast'
import { resolveStatementTypeName } from '@/constants/statementTypeLabels'

const { t, te } = useI18n()
const store = useStatementStore()
const {
  coins, types, records, filterLoading, recordLoading, hasMore,
  filterCoin, filterType, filterStart, filterEnd,
} = storeToRefs(store)
const toast = useToast()

onMounted(async () => {
  await store.loadFilters().catch(() => {})
  store.search(true).catch((e: unknown) => toast.error(e instanceof Error ? e.message : t('common.loadFailed')))
})

async function onSearch() {
  store.search(true).catch((e: unknown) => toast.error(e instanceof Error ? e.message : t('common.loadFailed')))
}

function onReset() {
  store.reset()
  store.search(true).catch(() => {})
}

function fmtAmount(r: typeof records.value[0]) {
  const n = Number(r.amount)
  return (n >= 0 ? '+' : '') + n.toFixed(4)
}

function recordTypeName(r: AssetStatement) {
  return resolveStatementTypeName(r.type, types.value, t, te)
}

function directionLabel(direction: string) {
  if (direction === '0') {
    return t('assets.statementDirectionOpen')
  }
  if (direction === '1') {
    return t('assets.statementDirectionClose')
  }
  return direction
}

const SHOW_DIRECTION = ['1', '19', '25']
</script>

<template>
  <main class="page-main">
    <div class="page-container content">
      <div class="page-header">
        <RouterLink to="/assets" class="back-link">{{ t('deposit.backWithArrow') }}</RouterLink>
        <h1 class="page-title">{{ t('assets.statementPageTitle') }}</h1>
      </div>

      <!-- 筛选区 -->
      <div class="filter-card dark-card">
        <div class="filter-row">
          <div class="filter-item">
            <label class="filter-label">{{ t('common.coin') }}</label>
            <select v-model="filterCoin" class="filter-select" :disabled="filterLoading">
              <option value="">{{ t('common.all') }}</option>
              <option v-for="c in coins" :key="c.code" :value="c.code">{{ c.name || c.code }}</option>
            </select>
          </div>
          <div class="filter-item">
            <label class="filter-label">{{ t('common.type') }}</label>
            <select v-model="filterType" class="filter-select" :disabled="filterLoading">
              <option value="">{{ t('common.all') }}</option>
              <option v-for="t in types" :key="t.typeId" :value="t.typeId">{{ t.name }}</option>
            </select>
          </div>
        </div>
        <div class="filter-row">
          <div class="filter-item">
            <label class="filter-label">{{ t('assets.statementStartDate') }}</label>
            <input v-model="filterStart" type="date" class="filter-input" />
          </div>
          <div class="filter-item">
            <label class="filter-label">{{ t('assets.statementEndDate') }}</label>
            <input v-model="filterEnd" type="date" class="filter-input" />
          </div>
        </div>
        <div class="filter-actions">
          <button class="reset-btn" @click="onReset">{{ t('assets.statementReset') }}</button>
          <button class="search-btn" :disabled="recordLoading" @click="onSearch">
            {{ recordLoading ? t('assets.statementSearching') : t('assets.statementSearch') }}
          </button>
        </div>
      </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('assets.statementEmpty') }}</p></div>

        <div v-else class="list dark-card">
          <div v-for="r in records" :key="r.id" class="record-row">
            <div class="rec-left">
              <p class="rec-type">
                {{ recordTypeName(r) }}
                <span v-if="SHOW_DIRECTION.includes(String(r.type)) && r.direction" class="dir-badge">
                  {{ directionLabel(String(r.direction)) }}
                </span>
              </p>
              <p class="rec-time">{{ r.createTime }}</p>
              <p v-if="Number(r.fee)" class="rec-fee">{{ t('withdraw.fee') }}: {{ r.fee }} {{ r.symbol }}</p>
            </div>
            <div class="rec-right">
              <span class="rec-amount" :class="Number(r.amount) >= 0 ? 'up' : 'down'">{{ fmtAmount(r) }}</span>
              <span class="rec-sym">{{ r.symbol }}</span>
            </div>
          </div>
        </div>

        <div class="load-more-wrap">
          <button v-if="hasMore" class="load-more-btn" :disabled="recordLoading" @click="store.search()">
            {{ 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: 800px; }
.page-header { margin-bottom: var(--space-8); }
.back-link { font-size: var(--text-small); color: var(--color-text-secondary); display: inline-block; margin-bottom: var(--space-3); }
.back-link:hover { color: var(--color-primary); }
.page-title { font-size: var(--text-h1); font-weight: var(--fw-bold); color: var(--color-text-primary); }
.filter-card { padding: var(--space-5); margin-bottom: var(--space-5); }
.filter-row { display: flex; gap: var(--space-4); margin-bottom: var(--space-4); flex-wrap: wrap; }
.filter-item { flex: 1; min-width: 160px; }
.filter-label { display: block; font-size: var(--text-caption); color: var(--color-text-secondary); margin-bottom: var(--space-1); }
.filter-select, .filter-input { width: 100%; box-sizing: border-box; background: var(--color-bg-card); border: 1px solid var(--color-border); border-radius: var(--radius-md); padding: var(--space-2) var(--space-3); color: var(--color-text-primary); font-size: var(--text-small); outline: none; }
.filter-select option { background: #1a1a1a; }
.filter-select:disabled { opacity: .5; }
.filter-actions { display: flex; gap: var(--space-3); justify-content: flex-end; }
.reset-btn { padding: var(--space-2) var(--space-6); background: transparent; border: 1px solid var(--color-border); border-radius: var(--radius-md); color: var(--color-text-secondary); cursor: pointer; font-size: var(--text-small); }
.reset-btn:hover { border-color: var(--color-text-secondary); }
.search-btn { padding: var(--space-2) var(--space-8); background: var(--color-primary); border: none; border-radius: var(--radius-md); color: #000; font-size: var(--text-small); font-weight: var(--fw-semibold); cursor: pointer; }
.search-btn:disabled { opacity: .5; cursor: not-allowed; }
.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); }
.record-row:last-child { border-bottom: none; }
.rec-type { 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; }
.dir-badge { font-size: var(--text-caption); background: var(--color-bg-card); color: var(--color-text-muted); padding: 1px 6px; border-radius: var(--radius-sm); }
.rec-time { font-size: var(--text-caption); color: var(--color-text-muted); }
.rec-fee { font-size: var(--text-caption); color: var(--color-text-muted); margin-top: 2px; }
.rec-right { text-align: right; }
.rec-amount { font-size: var(--text-body); font-weight: var(--fw-semibold); font-family: var(--font-family-num); display: block; }
.rec-amount.up   { color: var(--color-up); }
.rec-amount.down { color: var(--color-down); }
.rec-sym { font-size: var(--text-caption); color: var(--color-text-muted); }
.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>
