<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useWithdrawStore } from '@/stores/withdraw'
import type { WithdrawRecord } from '@/stores/withdraw'
import { useToast } from '@/composables/useToast'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const store = useWithdrawStore()
const toast = useToast()

const id = String(route.params.id)
const isTransfer = route.query.isTransfer === '1'
const record = ref<WithdrawRecord | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)

function statusText(st: string) {
  const m: Record<string, string> = {
    '0': t('withdraw.statusPending'),
    '1': t('withdraw.statusReleasing'),
    '2': t('withdraw.statusWithdrawFailed'),
    '3': t('withdraw.statusWithdrawSuccess'),
    '4': t('withdraw.statusWithdrawCancelled'),
  }
  return m[st] ?? st
}

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

const steps = computed(() => {
  const s = record.value?.status ?? '0'
  return [
    { label: t('withdraw.stepApplied'), done: true },
    {
      label: t('withdraw.statusPending'),
      done: ['1', '2', '3'].includes(s) || s === '4',
      failed: s === '4',
    },
    {
      label: t('withdraw.statusReleasing'),
      done: ['2', '3'].includes(s),
      failed: s === '2',
    },
    { label: t('withdraw.stepDone'), done: s === '3' },
  ]
})

const heroAmountText = computed(() => {
  if (!record.value) {
    return '--'
  }
  const v = (isTransfer ? record.value.transferAmount : record.value.amount)?.trim()
  if (!v) {
    return '--'
  }
  return `-${v}`
})

function trErr(msg: string | null) {
  if (!msg) {
    return ''
  }
  if (msg.startsWith('i18n:')) {
    return t(msg.slice(5))
  }
  return msg
}

onMounted(async () => {
  loading.value = true
  try {
    record.value = await store.fetchDetail(id, isTransfer)
  } catch (e) {
    error.value = e instanceof Error ? e.message : t('common.loadFailed')
    toast.error(trErr(error.value))
  } finally {
    loading.value = false
  }
})

async function cancel() {
  if (!record.value || !confirm(t('withdraw.confirmCancelApply'))) {
    return
  }
  try {
    await store.cancelRecord(record.value.id, isTransfer)
    toast.success(t('withdraw.withdrawCancelledToast'))
    router.back()
  } catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : t('withdraw.withdrawCancelFailedToast'))
  }
}

async function copyText(text: string) {
  await navigator.clipboard.writeText(text)
  toast.success(t('common.copied'))
}
</script>

<template>
  <main class="page-main">
    <div class="page-container content">
      <div class="page-header">
        <button class="back-link" @click="router.back()">{{ t('deposit.backWithArrow') }}</button>
        <h1 class="page-title">{{ isTransfer ? t('withdraw.detailTitleTransfer') : t('withdraw.detailTitleOnChain') }}</h1>
      </div>

      <div v-if="loading" class="loading-state"><div class="spinner" /></div>
      <div v-else-if="error" class="error-state dark-card"><p>{{ trErr(error) }}</p></div>

      <template v-else-if="record">
        <div class="amount-hero dark-card">
          <p class="hero-label">{{ isTransfer ? t('withdraw.amountHeroTransfer') : t('withdraw.amountHeroWithdraw') }}</p>
          <p class="hero-amount">
            {{ heroAmountText }}
            <span class="hero-unit">USDT</span>
          </p>
          <span class="status-badge" :class="STATUS_CLASS[record.status] ?? 'pending'">
            {{ statusText(record.status) }}
          </span>
        </div>

        <div v-if="!isTransfer" class="steps-card dark-card">
          <div class="steps">
            <div v-for="(step, i) in steps" :key="i" class="step">
              <div class="step-icon" :class="{ done: step.done, failed: step.failed }">
                {{ step.failed ? '✕' : step.done ? '✓' : i + 1 }}
              </div>
              <p class="step-label">{{ step.label }}</p>
              <div v-if="i < steps.length - 1" class="step-line" :class="{ active: step.done && !step.failed }" />
            </div>
          </div>
        </div>

        <div class="detail-card dark-card">
          <div class="detail-row">
            <span class="detail-label">{{ isTransfer ? t('common.type') : t('withdraw.network') }}</span>
            <span class="detail-val">{{ isTransfer ? t('withdraw.typeInternalTransfer') : (record.coin?.aliasName || 'USDT') }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">{{ isTransfer ? t('withdraw.recipientLabel') : t('withdraw.address') }}</span>
            <div class="copy-row">
              <span class="detail-val mono">{{ record.address }}</span>
              <button v-if="record.address" class="copy-btn" @click="copyText(record.address)">{{ t('withdraw.copyBtn') }}</button>
            </div>
          </div>
          <div v-if="!isTransfer && record.transactionHashId" class="detail-row">
            <span class="detail-label">TXID</span>
            <div class="copy-row">
              <span class="detail-val mono small">{{ record.transactionHashId.slice(0, 20) }}…</span>
              <button class="copy-btn" @click="copyText(record.transactionHashId)">{{ t('withdraw.copyBtn') }}</button>
            </div>
          </div>
          <div v-if="!isTransfer && record.coin?.fee" class="detail-row">
            <span class="detail-label">{{ t('withdraw.fee') }}</span>
            <span class="detail-val">{{ record.coin.fee }} USDT</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">{{ t('withdraw.appliedAt') }}</span>
            <span class="detail-val">{{ record.createTime }}</span>
          </div>
          <div v-if="record.dealTime" class="detail-row">
            <span class="detail-label">{{ t('withdraw.finishedAt') }}</span>
            <span class="detail-val">{{ record.dealTime }}</span>
          </div>
        </div>

        <button v-if="record.status === '0'" class="cancel-btn" @click="cancel">{{ t('withdraw.cancelApplyFull') }}</button>
      </template>
    </div>
  </main>
</template>

<style scoped>
.content { padding-top: var(--space-8); padding-bottom: var(--space-16); max-width: 600px; }
.page-header { margin-bottom: var(--space-8); }
.back-link { background: none; border: none; font-size: var(--text-small); color: var(--color-text-secondary); cursor: pointer; 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); }
.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); } }
.error-state { padding: var(--space-8); text-align: center; color: var(--color-text-secondary); }
.amount-hero { padding: var(--space-8) var(--space-6); text-align: center; margin-bottom: var(--space-4); }
.hero-label { font-size: var(--text-small); color: var(--color-text-secondary); margin-bottom: var(--space-3); }
.hero-amount { font-size: 36px; font-weight: var(--fw-bold); font-family: var(--font-family-num); color: var(--color-text-primary); margin-bottom: var(--space-3); }
.hero-unit { font-size: var(--text-body); font-weight: var(--fw-normal); color: var(--color-text-secondary); }
.status-badge { display: inline-block; font-size: var(--text-small); font-weight: var(--fw-semibold); padding: 4px 12px; border-radius: var(--radius-md); }
.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); }
.steps-card { padding: var(--space-6); margin-bottom: var(--space-4); }
.steps { display: flex; align-items: flex-start; }
.step { display: flex; flex-direction: column; align-items: center; flex: 1; position: relative; }
.step-icon { width: 28px; height: 28px; border-radius: 50%; border: 1px solid var(--color-border); display: flex; align-items: center; justify-content: center; font-size: var(--text-small); color: var(--color-text-muted); background: var(--color-bg-card); margin-bottom: var(--space-2); }
.step-icon.done { background: var(--color-primary); border-color: var(--color-primary); color: #000; font-weight: var(--fw-bold); }
.step-icon.failed { background: var(--color-down); border-color: var(--color-down); color: #fff; }
.step-label { font-size: var(--text-caption); color: var(--color-text-muted); text-align: center; }
.step-line { position: absolute; top: 14px; left: calc(50% + 14px); width: calc(100% - 28px); height: 1px; background: var(--color-border); }
.step-line.active { background: var(--color-primary); }
.detail-card { margin-bottom: var(--space-4); overflow: hidden; }
.detail-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); gap: var(--space-4); }
.detail-row:last-child { border-bottom: none; }
.detail-label { font-size: var(--text-small); color: var(--color-text-secondary); flex-shrink: 0; }
.detail-val { font-size: var(--text-small); color: var(--color-text-primary); text-align: right; }
.detail-val.mono { font-family: var(--font-family-num); word-break: break-all; }
.detail-val.small { font-size: var(--text-caption); }
.copy-row { display: flex; align-items: center; gap: var(--space-2); }
.copy-btn { background: none; border: 1px solid var(--color-primary); border-radius: var(--radius-sm); color: var(--color-primary); font-size: var(--text-caption); padding: 2px 8px; cursor: pointer; flex-shrink: 0; }
.cancel-btn { width: 100%; padding: var(--space-4); background: transparent; border: 1px solid var(--color-down); border-radius: var(--radius-md); color: var(--color-down); font-size: var(--text-body); font-weight: var(--fw-semibold); cursor: pointer; margin-top: var(--space-4); }
</style>
