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

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

const router = useRouter()

const { data: overviewData, isLoading } = useGetFinanceOverviewQuery()
const overview = computed(() => overviewData.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: 资金流动 ==========
const flowMetrics = computed(() => [
  {
    label: '累计充值',
    value: overview.value?.totalDeposit || 0,
    icon: 'lucide:arrow-down-circle',
    color: 'text-green-600',
    bgColor: 'bg-green-50 dark:bg-green-950',
    trend: '+12.5%',
  },
  {
    label: '累计提现',
    value: overview.value?.totalWithdraw || 0,
    icon: 'lucide:arrow-up-circle',
    color: 'text-red-600',
    bgColor: 'bg-red-50 dark:bg-red-950',
    trend: '+8.3%',
  },
  {
    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: '+15.2%',
  },
])

// ========== 模块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: ['1月', '2月', '3月', '4月', '5月', '6月'],
  },
  yAxis: {
    type: 'value',
    axisLabel: { formatter: '¥{value}K' },
  },
  series: [
    {
      name: '充值',
      type: 'line',
      smooth: true,
      data: [320, 302, 301, 334, 390, 430],
      itemStyle: { color: '#10b981' },
      areaStyle: { color: 'rgba(16, 185, 129, 0.1)' },
    },
    {
      name: '提现',
      type: 'line',
      smooth: true,
      data: [120, 132, 101, 134, 90, 230],
      itemStyle: { color: '#ef4444' },
      areaStyle: { color: 'rgba(239, 68, 68, 0.1)' },
    },
  ],
}))

// ========== 模块4: 资金分布 ==========
const distributionOption = computed(() => ({
  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: overview.value?.fundBalance || 50, name: '在管资金', itemStyle: { color: '#3b82f6' } },
      { value: overview.value?.tradeValue || 30, name: '交易账户', itemStyle: { color: '#8b5cf6' } },
      { value: 20, name: '冻结资金', itemStyle: { color: '#f59e0b' } },
    ],
  }],
}))

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

      <!-- 模块2: 资金流动 -->
      <section>
        <h2 class="text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2">
          <Icon icon="lucide:git-compare" class="size-4" />
          资金流动
        </h2>
        <div class="grid gap-3 sm:grid-cols-3">
          <UiCard v-for="item in flowMetrics" :key="item.label" class="hover:shadow-sm transition-shadow">
            <UiCardContent class="pt-6">
              <div class="flex items-center justify-between">
                <div class="p-2.5 rounded-lg" :class="[item.bgColor]">
                  <Icon :icon="item.icon" class="size-5" :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-2xl font-bold font-mono" :class="item.color">
                  {{ formatCurrency(item.value) }}
                </p>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </section>

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

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

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

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

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

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

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