<template>
  <div
    class="lucid-glass-bar flex h-full w-full flex-col rounded-4xl! border-1 border-white px-6 py-7"
  >
    <div class="mb-[20px] flex justify-between border-b-1 border-dashed pb-4">
      <div>
        <div class="mb-1 text-base font-bold text-white">退费数据</div>
      </div>
      <Button
        variant="link"
        class="h-auto p-0 text-sm font-medium text-white/60 underline hover:text-white"
        @click="$emit('show-history')"
      >
        查看全部
      </Button>
    </div>

    <div class="flex-1 overflow-y-auto pr-1">
      <div v-if="loading" class="flex h-10 items-center justify-center">
        <div
          class="h-6 w-6 animate-spin rounded-full border-2 border-[#ADFF5B] border-t-transparent"
        ></div>
      </div>
      <div v-else class="">
        <div
          v-for="(item, index) in salesPage.list"
          :key="index"
          class="mb-3 flex items-center justify-between last:mb-0"
        >
          <div class="flex flex-col">
            <span class="text-sm font-semibold text-white">{{ item.id }}</span>
            <span class="text-[10px] text-white/40">{{ formatTime(item.created_at) }}</span>
          </div>
          <div class="text-lg font-bold text-white tabular-nums">
            $ {{ formatAmount(item.amount) }}
          </div>
        </div>
        <div v-if="!salesPage.list.length">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Button } from '@/components/ui/button'
import request from '@/utils/request'

defineEmits(['show-history'])

const salesPage = ref({
  total: 0,
  list: [] as any[],
})
function formatAmount(amount: number) {
  return ((amount || 0) / 100).toFixed(2)
}

function formatTime(timestamp: number) {
  if (!timestamp) return '-'
  const date = new Date(timestamp > 10000000000 ? timestamp : timestamp * 1000)
  return date.toLocaleString('zh-CN', {
    month: 'numeric',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  })
}

const loading = ref(false)

async function fetchSales() {
  loading.value = true
  try {
    const res: any = await request.get('/api/v1/public/user/withdrawal_log', {
      page: 1,
      size: 2,
      biz_type: 'commission_refund',
    })
    salesPage.value = res
  } catch (error) {
    console.error('Fetch sales error:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchSales()
})
</script>
