'use client';

/**
 * 仪表板页面
 * [2026-01-06] 更新：统计卡片和趋势图改用 planting-service 数据（源数据）
 * [2026-01-07] 更新：添加热钱包余额显示（网络因子、加速因子）
 */

import { useState } from 'react';
import { Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { StatCard } from '@/components/features/dashboard/StatCard';
import { TrendChart } from '@/components/features/dashboard/TrendChart';
import { RegionDistribution } from '@/components/features/dashboard/RegionDistribution';
import { RecentActivity } from '@/components/features/dashboard/RecentActivity';
import {
  useDashboardRegion,
  useDashboardActivities,
  usePlantingStats,
  usePlantingTrendForDashboard,
  useHotWalletBalance,
  usePrePlantingStats,
} from '@/hooks';
import type { DashboardPeriod } from '@/types';
import styles from './dashboard.module.scss';

// 骨架屏组件
const StatCardSkeleton = () => (
  <div className={styles.dashboard__skeleton}>
    <div className={styles.dashboard__skeletonTitle} />
    <div className={styles.dashboard__skeletonValue} />
    <div className={styles.dashboard__skeletonChange} />
  </div>
);

// 错误提示组件
const ErrorMessage = ({ message, onRetry }: { message: string; onRetry?: () => void }) => (
  <div className={styles.dashboard__error}>
    <span>{message}</span>
    {onRetry && (
      <Button variant="outline" size="sm" onClick={onRetry}>
        重试
      </Button>
    )}
  </div>
);

// 空数据提示
const EmptyData = ({ message }: { message: string }) => (
  <div className={styles.dashboard__empty}>
    <span>{message}</span>
  </div>
);

/** 将 DashboardPeriod 转换为天数 */
function periodToDays(period: DashboardPeriod): 7 | 30 | 90 {
  switch (period) {
    case '7d': return 7;
    case '30d': return 30;
    case '90d': return 90;
    default: return 7;
  }
}

export default function DashboardPage() {
  const [trendPeriod, setTrendPeriod] = useState<DashboardPeriod>('7d');

  // [2026-01-06] 直接使用 planting-service 数据（源数据）
  const {
    data: plantingStatsData,
    isLoading: statsLoading,
    error: statsError,
    refetch: refetchStats,
  } = usePlantingStats();

  // [2026-01-06] 趋势数据也使用 planting-service
  const {
    data: trendData,
    isLoading: trendLoading,
    error: trendError,
    refetch: refetchTrend,
  } = usePlantingTrendForDashboard(periodToDays(trendPeriod));

  const {
    data: regionData,
    isLoading: regionLoading,
    error: regionError,
    refetch: refetchRegion,
  } = useDashboardRegion();

  const {
    data: activitiesData,
    isLoading: activitiesLoading,
    error: activitiesError,
    refetch: refetchActivities,
  } = useDashboardActivities(5);

  // [2026-01-07] 热钱包余额（网络因子、加速因子）
  const {
    data: hotWalletData,
    isLoading: hotWalletLoading,
  } = useHotWalletBalance();

  // 预种统计（待合并/已合并）
  const {
    data: prePlantingStats,
    isLoading: prePlantingStatsLoading,
  } = usePrePlantingStats();

  // [2026-01-06] 基于 planting-service 数据构建统计卡片数据
  const statsCards = plantingStatsData ? [
    {
      title: '总认种量',
      value: plantingStatsData.totalTreeCount,
      suffix: '棵',
      change: { value: plantingStatsData.todayStats?.treeCount ?? 0, trend: 'up' as const },
      color: '#10b981',
    },
    {
      title: '总订单数',
      value: plantingStatsData.totalOrderCount,
      suffix: '单',
      change: { value: plantingStatsData.todayStats?.orderCount ?? 0, trend: 'up' as const },
      color: '#3b82f6',
    },
    {
      title: '今日认种',
      value: plantingStatsData.todayStats?.treeCount ?? 0,
      suffix: '棵',
      change: { value: 0, trend: 'up' as const },
      color: '#f59e0b',
    },
    {
      title: '本月认种',
      value: plantingStatsData.monthStats?.treeCount ?? 0,
      suffix: '棵',
      change: { value: 0, trend: 'up' as const },
      color: '#8b5cf6',
    },
    {
      title: '预种待合并',
      value: prePlantingStats?.pendingMergePortions ?? 0,
      suffix: '份',
      change: { value: 0, trend: 'up' as const },
      color: '#ef4444',
    },
    {
      title: '预种已合并',
      value: prePlantingStats?.totalTreesMerged ?? 0,
      suffix: '棵',
      change: { value: 0, trend: 'up' as const },
      color: '#06b6d4',
    },
  ] : [];

  const headerActions = (
    <>
      <Button variant="outline" size="sm">
        添加用户
      </Button>
      <Button variant="outline" size="sm">
        授权管理
      </Button>
      <Button variant="primary" size="sm">
        查看报表
      </Button>
    </>
  );

  return (
    <PageContainer
      title="仪表板"
      breadcrumb={[{ label: '首页', path: '/' }, { label: '仪表板' }]}
      actions={headerActions}
    >
      <div className={styles.dashboard}>
        {/* 统计卡片区 - [2026-01-06] 使用 planting-service 数据 */}
        <div className={styles.dashboard__stats}>
          {statsLoading ? (
            // 加载状态显示骨架屏
            <>
              {[1, 2, 3, 4, 5, 6].map((i) => (
                <StatCardSkeleton key={i} />
              ))}
            </>
          ) : statsError ? (
            // 错误状态
            <div className={styles.dashboard__statsError}>
              <ErrorMessage
                message="加载统计数据失败"
                onRetry={() => refetchStats()}
              />
            </div>
          ) : statsCards.length > 0 ? (
            // 正常显示数据（直接使用 planting-service 源数据）
            statsCards.map((stat, index) => (
              <StatCard key={index} {...stat} />
            ))
          ) : (
            // 空数据状态
            <EmptyData message="暂无统计数据" />
          )}
        </div>

        {/* [2026-01-07] 新增：热钱包余额区域 */}
        <div className={styles.dashboard__walletBalance}>
          <div className={styles.dashboard__walletCard}>
            <div className={styles.dashboard__walletLabel}>网络因子</div>
            <div className={styles.dashboard__walletValue}>
              {hotWalletLoading ? (
                <span className={styles.dashboard__walletLoading}>加载中...</span>
              ) : hotWalletData?.dusdtBalance ? (
                <span className={styles.dashboard__walletAmount}>
                  {parseFloat(hotWalletData.dusdtBalance).toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  })}
                </span>
              ) : (
                <span className={styles.dashboard__walletNA}>--</span>
              )}
            </div>
          </div>
          <div className={styles.dashboard__walletCard}>
            <div className={styles.dashboard__walletLabel}>加速因子</div>
            <div className={styles.dashboard__walletValue}>
              {hotWalletLoading ? (
                <span className={styles.dashboard__walletLoading}>加载中...</span>
              ) : hotWalletData?.nativeBalance ? (
                <span className={styles.dashboard__walletAmount}>
                  {parseFloat(hotWalletData.nativeBalance).toLocaleString('zh-CN', {
                    minimumFractionDigits: 4,
                    maximumFractionDigits: 4
                  })}
                </span>
              ) : (
                <span className={styles.dashboard__walletNA}>--</span>
              )}
            </div>
          </div>
        </div>

        {/* 图表区 - [2026-01-06] 使用 planting-service 数据 */}
        <div className={styles.dashboard__charts}>
          <div className={styles.dashboard__mainChart}>
            {trendError ? (
              <ErrorMessage
                message="加载趋势数据失败"
                onRetry={() => refetchTrend()}
              />
            ) : (
              <TrendChart
                title="认种趋势"
                data={trendData ?? []}
                period={trendPeriod}
                onPeriodChange={setTrendPeriod}
                loading={trendLoading}
              />
            )}
          </div>
          <div className={styles.dashboard__sidePanel}>
            {activitiesLoading ? (
              <div className={styles.dashboard__activitiesLoading}>加载中...</div>
            ) : activitiesError ? (
              <ErrorMessage
                message="加载活动数据失败"
                onRetry={() => refetchActivities()}
              />
            ) : (
              <RecentActivity activities={activitiesData ?? []} />
            )}
          </div>
        </div>

        {/* 底部区域 */}
        <div className={styles.dashboard__bottom}>
          <div className={styles.dashboard__regionChart}>
            {regionLoading ? (
              <div className={styles.dashboard__regionLoading}>加载中...</div>
            ) : regionError ? (
              <ErrorMessage
                message="加载区域分布数据失败"
                onRetry={() => refetchRegion()}
              />
            ) : regionData && regionData.length > 0 ? (
              <RegionDistribution data={regionData} />
            ) : (
              <EmptyData message="暂无区域分布数据" />
            )}
          </div>
        </div>
      </div>
    </PageContainer>
  );
}
