<script setup lang="ts">
import { ArrowDownLeft, ArrowUpRight, Loader2, Receipt, RotateCcw, TrendingDown, TrendingUp, Wallet } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'

import type { Transaction } from '@/pages/agent/finance/data/schema'

import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/agent/finance/components/data-table.vue'
import api from '@/services/api'

const { t } = useI18n()

const loading = ref(true)
const balance = ref(0)
const transactions = ref<Transaction[]>([])
const tableRef = ref()
const typeFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const rechargeCount = ref(0)
const consumeCount = ref(0)
const totalRecharge = ref(0)
const totalConsume = ref(0)

const serverPagination = computed(() => ({
  page: currentPage.value,
  pageSize: pageSize.value,
  total: total.value,
  onPageChange: (newPage: number) => {
    currentPage.value = newPage
    fetchFinance()
  },
  onPageSizeChange: (newPageSize: number) => {
    pageSize.value = newPageSize
    currentPage.value = 1
    fetchFinance()
  },
}))

async function fetchFinance() {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', String(currentPage.value))
    params.append('page_size', String(pageSize.value))
    if (typeFilter.value) {
      params.append('type', typeFilter.value)
    }

    const data = await api.get<any>(`/agent/finance?${params.toString()}`)
    if (data) {
      balance.value = data.balance || 0
      transactions.value = data.transactions || []
      total.value = data.total || 0
      rechargeCount.value = data.recharge_count || 0
      consumeCount.value = data.consume_count || 0
      totalRecharge.value = data.total_recharge || 0
      totalConsume.value = data.total_consume || 0
    }
  }
  catch (error) {
    console.error('Load finance data failed:', error)
    transactions.value = []
  }
  finally {
    loading.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('agent.finance.title')"
    :description="t('agent.finance.description')"
    :breadcrumbs="[
      { title: t('nav.dashboard'), href: '/agent' },
      { title: t('nav.finance') },
    ]"
    sticky
  >
    <div class="space-y-6">
      <div class="grid gap-4 md:grid-cols-3 lg:grid-cols-5">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.finance.balance') }}
            </UiCardTitle>
            <Wallet class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              ¥{{ balance.toFixed(2) }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.finance.rechargeCount') }}
            </UiCardTitle>
            <ArrowDownLeft class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ rechargeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.finance.rechargeAmount') }}
            </UiCardTitle>
            <TrendingUp class="size-4 text-green-500" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold text-green-500">
              +¥{{ totalRecharge.toFixed(2) }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.finance.consumeCount') }}
            </UiCardTitle>
            <ArrowUpRight class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ consumeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.finance.consumeAmount') }}
            </UiCardTitle>
            <TrendingDown class="size-4 text-red-500" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold text-red-500">
              -¥{{ totalConsume.toFixed(2) }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardHeader>
          <UiCardTitle class="flex items-center gap-2">
            <Receipt class="size-5" />
            {{ t('agent.finance.transactions') }}
          </UiCardTitle>
          <UiCardDescription>
            {{ t('agent.finance.transactionsDesc') }}
          </UiCardDescription>
        </UiCardHeader>
        <UiCardContent class="p-6">
          <div v-if="loading" class="flex items-center justify-center py-12">
            <Loader2 class="size-8 animate-spin text-muted-foreground" />
          </div>

          <DataTable
            v-else
            ref="tableRef"
            :loading
            :data="transactions"
            :server-pagination="serverPagination"
            :type-filter="typeFilter"
            @refresh="fetchFinance"
            @update:typeFilter="typeFilter = $event; currentPage = 1; fetchFinance()"
          />
        </UiCardContent>
      </UiCard>
    </div>
  </BasicPage>
</template>
