<script lang="ts" setup>
import Decimal from 'decimal.js'
import { Icon } from '@iconify/vue'
import VChart from 'vue-echarts'
import { useRouter } from 'vue-router'

import { BasicPage } from '@/components/global-layout'
import { useGetCashFlowTrendQuery, useGetFinanceOverviewQuery } from '@/services/api/monisuo-admin.api'

const router = useRouter()

const { data: overviewData, isLoading: overviewLoading } = useGetFinanceOverviewQuery()
const { data: cashFlowData, isLoading: cashFlowLoading } = useGetCashFlowTrendQuery(6)

const isLoading = computed(() => overviewLoading.value || cashFlowLoading.value)
const overview = computed(() => overviewData.value?.data)
const cashFlow = computed(() => cashFlowData.value?.data || [])

// ========== 模块1: 资金概览 ==========
const fundMetrics = computed(() => [
  {
    label: '在管资金',
    value: overview.value?.fundBalance || 0,
    icon: 'lucide:wallet',
    color: 'text-blue-600',
    bgColor: 'bg-blue-50 dark:bg-blue-950',
  },
  {
    label: '交易账户',
    value: overview.value?.tradeValue || 0,
    icon: 'lucide:bar-chart-3',
    color: 'text-purple-600',
    bgColor: 'bg-purple-50 dark:bg-purple-950',
  },
  {
    label: '总资产',
    value: (overview.value?.fundBalance || 0) + (overview.value?.tradeValue || 0),
    icon: 'lucide:landmark',
    color: 'text-orange-600',
    bgColor: 'bg-orange-50 dark:bg-orange-950',
  },
])

// ========== 模块2: 资金流动 ==========
function calcGrowthRate(current: number, previous: number): string {
  if (previous === 0)
    return current > 0 ? '+100%' : '0%'
  const rate = new Decimal(current).minus(previous).div(previous).mul(100).toDecimalPlaces(1)
  const sign = rate.gte(0) ? '+' : ''
  return `${sign}${rate}%`
}

const flowMetrics = computed(() => {
  const flow = cashFlow.value
  const len = flow.length
  const thisMonth = len >= 1 ? flow[len - 1] : null
  const lastMonth = len >= 2 ? flow[len - 2] : null

  const depositTrend = thisMonth && lastMonth
    ? calcGrowthRate(thisMonth.deposit as number, lastMonth.deposit as number)
    : '+0%'
  const withdrawTrend = thisMonth && lastMonth
    ? calcGrowthRate(thisMonth.withdraw as number, lastMonth.withdraw as number)
    : '+0%'
  const netInflowTrend = thisMonth && lastMonth
    ? calcGrowthRate(thisMonth.netInflow as number, lastMonth.netInflow as number)
    : '+0%'

  return [
    {
      label: '累计充值',
      value: overview.value?.totalDeposit || 0,
      icon: 'lucide:arrow-down-circle',
      color: 'text-green-600',
      bgColor: 'bg-green-50 dark:bg-green-950',
      trend: depositTrend,
    },
    {
      label: '累计提现',
      value: overview.value?.totalWithdraw || 0,
      icon: 'lucide:arrow-up-circle',
      color: 'text-red-600',
      bgColor: 'bg-red-50 dark:bg-red-950',
      trend: withdrawTrend,
    },
    {
      label: '净流入',
      value: (overview.value?.totalDeposit || 0) - (overview.value?.totalWithdraw || 0),
      icon: 'lucide:trending-up',
      color: 'text-emerald-600',
      bgColor: 'bg-emerald-50 dark:bg-emerald-950',
      trend: netInflowTrend,
    },
  ]
})

// ========== 模块3: 资金趋势图 ==========
const trendChartOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  legend: { data: ['充值', '提现'], bottom: 0, top: 'auto' },
  grid: { left: '3%', right: '4%', bottom: '15%', top: '5%', containLabel: true },
  xAxis: {
    type: 'category',
    data: cashFlow.value.map((t: any) => t.month),
  },
  yAxis: {
    type: 'value',
    axisLabel: { formatter: '¥{value}K' },
  },
  series: [
    {
      name: '充值',
      type: 'line',
      smooth: true,
      data: cashFlow.value.map((t: any) => t.deposit),
      itemStyle: { color: '#10b981' },
      areaStyle: { color: 'rgba(16, 185, 129, 0.1)' },
    },
    {
      name: '提现',
      type: 'line',
      smooth: true,
      data: cashFlow.value.map((t: any) => t.withdraw),
      itemStyle: { color: '#ef4444' },
      areaStyle: { color: 'rgba(239, 68, 68, 0.1)' },
    },
  ],
}))

// ========== 模块4: 资金分布 ==========
const distributionOption = computed(() => {
  const fundBalance = overview.value?.fundBalance || 0
  const tradeValue = overview.value?.tradeValue || 0

  return {
    tooltip: { trigger: 'item', formatter: '{b}: {d}%' },
    legend: { orient: 'vertical', right: '5%', top: 'center' },
    series: [{
      type: 'pie',
      radius: ['50%', '75%'],
      center: ['35%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
      label: { show: true, position: 'inside', formatter: '{d}%', fontSize: 12 },
      data: [
        { value: fundBalance, name: '在管资金', itemStyle: { color: '#3b82f6' } },
        { value: tradeValue, name: '交易账户', itemStyle: { color: '#8b5cf6' } },
      ],
    }],
  }
})

// ========== 模块5: 运营指标 ==========
const operationMetrics = computed(() => [
  { label: '用户总数', value: overview.value?.userCount || 0, icon: 'lucide:users' },
  { label: '待审批', value: overview.value?.pendingCount || 0, icon: 'lucide:clock' },
])

function formatCurrency(value: number): string {
  if (value >= 10000)
    return `¥${(value / 10000).toFixed(1)}万`
  return `¥${value.toLocaleString()}`
}

function navigateTo(path: string) {
  router.push(path)
}
</script>

<template>
  <BasicPage title="数据看板" description="核心业务数据一目了然">
    <div v-if="isLoading" class="flex items-center justify-center py-20">
      <UiSpinner class="w-8 h-8" />
    </div>

    <div v-else class="grid gap-6">
      <!-- 模块1: 资金概览 -->
      <section class="space-y-3">
        <h2 class="text-sm font-medium text-muted-foreground flex items-center gap-2">
          <Icon icon="lucide:wallet" class="size-4" />
          资金概览
        </h2>
        <div class="grid gap-3 grid-cols-1 sm:grid-cols-3">
          <UiCard v-for="item in fundMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
            <UiCardContent class="p-4">
              <div class="flex items-center justify-between">
                <div class="p-2 rounded-lg" :class="[item.bgColor]">
                  <Icon :icon="item.icon" class="size-4" :class="item.color" />
                </div>
              </div>
              <div class="mt-3 space-y-1">
                <p class="text-xs text-muted-foreground">
                  {{ item.label }}
                </p>
                <p class="text-lg sm:text-xl font-bold font-mono truncate" :class="item.color">
                  {{ formatCurrency(item.value) }}
                </p>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </section>

      <!-- 模块2: 资金流动 -->
      <section class="space-y-3">
        <h2 class="text-sm font-medium text-muted-foreground flex items-center gap-2">
          <Icon icon="lucide:git-compare" class="size-4" />
          资金流动
        </h2>
        <div class="grid gap-3 grid-cols-1 sm:grid-cols-3">
          <UiCard v-for="item in flowMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
            <UiCardContent class="p-4">
              <div class="flex items-center justify-between">
                <div class="p-2 rounded-lg" :class="[item.bgColor]">
                  <Icon :icon="item.icon" class="size-4" :class="item.color" />
                </div>
                <span class="text-xs font-medium text-green-600">{{ item.trend }}</span>
              </div>
              <div class="mt-3 space-y-1">
                <p class="text-xs text-muted-foreground">
                  {{ item.label }}
                </p>
                <p class="text-lg sm:text-xl font-bold font-mono truncate" :class="item.color">
                  {{ formatCurrency(item.value) }}
                </p>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </section>

      <!-- 模块3+4: 图表区域 -->
      <div class="grid gap-6 lg:grid-cols-2">
        <!-- 资金趋势 -->
        <section class="space-y-3">
          <h2 class="text-sm font-medium text-muted-foreground flex items-center gap-2">
            <Icon icon="lucide:trending-up" class="size-4" />
            资金趋势
          </h2>
          <UiCard>
            <UiCardContent class="p-4">
              <VChart :option="trendChartOption" autoresize style="height: 240px" />
            </UiCardContent>
          </UiCard>
        </section>

        <!-- 资金分布 -->
        <section class="space-y-3">
          <h2 class="text-sm font-medium text-muted-foreground flex items-center gap-2">
            <Icon icon="lucide:pie-chart" class="size-4" />
            资金分布
          </h2>
          <UiCard>
            <UiCardContent class="p-4">
              <VChart :option="distributionOption" autoresize style="height: 240px" />
            </UiCardContent>
          </UiCard>
        </section>
      </div>

      <!-- 模块5: 运营指标 + 快捷入口 -->
      <div class="grid gap-6 lg:grid-cols-5">
        <!-- 运营指标 -->
        <section class="space-y-3 lg:col-span-2">
          <h2 class="text-sm font-medium text-muted-foreground flex items-center gap-2">
            <Icon icon="lucide:activity" class="size-4" />
            运营指标
          </h2>
          <div class="grid gap-3 grid-cols-2">
            <UiCard v-for="item in operationMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
              <UiCardContent class="p-4">
                <div class="flex items-center justify-between">
                  <div class="min-w-0">
                    <p class="text-xs text-muted-foreground truncate">
                      {{ item.label }}
                    </p>
                    <p class="text-lg sm:text-xl font-bold mt-1 truncate">
                      {{ item.value }}
                    </p>
                  </div>
                  <Icon :icon="item.icon" class="size-6 text-muted-foreground/30 shrink-0" />
                </div>
              </UiCardContent>
            </UiCard>
          </div>
        </section>

        <!-- 快捷入口 -->
        <section class="space-y-3 lg:col-span-3">
          <h2 class="text-sm font-medium text-muted-foreground flex items-center gap-2">
            <Icon icon="lucide:zap" class="size-4" />
            快捷入口
          </h2>
          <div class="grid gap-3 grid-cols-2 sm:grid-cols-4">
            <UiCard
              class="cursor-pointer hover:shadow-md hover:border-primary/50 transition-all"
              @click="navigateTo('/monisuo/users')"
            >
              <UiCardContent class="p-4 text-center">
                <Icon icon="lucide:users" class="size-6 mx-auto mb-2 text-blue-600" />
                <p class="text-sm font-medium">
                  用户管理
                </p>
              </UiCardContent>
            </UiCard>

            <UiCard
              class="cursor-pointer hover:shadow-md hover:border-primary/50 transition-all"
              @click="navigateTo('/monisuo/coins')"
            >
              <UiCardContent class="p-4 text-center">
                <Icon icon="lucide:coins" class="size-6 mx-auto mb-2 text-yellow-600" />
                <p class="text-sm font-medium">
                  币种管理
                </p>
              </UiCardContent>
            </UiCard>

            <UiCard
              class="cursor-pointer hover:shadow-md hover:border-primary/50 transition-all"
              @click="navigateTo('/monisuo/orders')"
            >
              <UiCardContent class="p-4 text-center">
                <Icon icon="lucide:clipboard-check" class="size-6 mx-auto mb-2 text-green-600" />
                <p class="text-sm font-medium">
                  订单审批
                </p>
              </UiCardContent>
            </UiCard>

            <UiCard
              class="cursor-pointer hover:shadow-md hover:border-primary/50 transition-all"
              @click="navigateTo('/monisuo/analytics')"
            >
              <UiCardContent class="p-4 text-center">
                <Icon icon="lucide:trending-up" class="size-6 mx-auto mb-2 text-purple-600" />
                <p class="text-sm font-medium">
                  业务分析
                </p>
              </UiCardContent>
            </UiCard>
          </div>
        </section>
      </div>
    </div>
  </BasicPage>
</template>
