import { useEffect, useState, useCallback } from 'react';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import { LineChart, BarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, LegendComponent, DataZoomComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { adminApi } from '../lib/api';
import type { AdminStats } from '../types';
import { showToast } from '../components/Toast';
import { c } from '../lib/themeColor';
import { useThemeStore } from '../store/theme';
import styles from './DashboardPage.module.css';

echarts.use([LineChart, BarChart, GridComponent, TooltipComponent, LegendComponent, DataZoomComponent, CanvasRenderer]);

export function DashboardPage() {
  const [stats, setStats] = useState<AdminStats | null>(null);
  const [loading, setLoading] = useState(true);
  // theme 变化时强制 ECharts 重渲染（option 里 c() 读 CSS var；
  // 订阅 theme 触发本组件 re-render，并用 key 让图表 unmount→remount）
  const theme = useThemeStore((s) => s.theme);

  const fetchData = useCallback(async () => {
    try {
      const { data } = await adminApi.getStats();
      setStats(data);
    } catch {
      showToast('加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchData(); }, [fetchData]);

  if (loading) {
    return (
      <div className={styles.page}>
        <div className={styles.skeleton}>
          <div className={styles.skeletonCards}>
            {[1, 2, 3, 4].map((i) => <div key={i} className={styles.skeletonCard} />)}
          </div>
          <div className={styles.skeletonChart} />
          <div className={styles.skeletonChart} />
        </div>
      </div>
    );
  }

  if (!stats) return null;

  const statCards = [
    { label: '总团队数', value: String(stats.total_teams), change: null },
    { label: '总用户数', value: String(stats.total_users), change: null },
    { label: '今日消费', value: `¥${(stats.cost_today || 0).toFixed(2)}`, change: stats.today_change_percent },
    { label: '本月消费', value: `¥${(stats.cost_this_month || 0).toFixed(2)}`, change: stats.month_change_percent },
  ];

  const trendOption: echarts.EChartsCoreOption = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: c('tooltip-bg'),
      borderColor: c('tooltip-border'),
      textStyle: { color: c('text-primary'), fontSize: 12 },
      formatter: (params: unknown) => {
        const p = (params as { name: string; value: number }[])[0];
        return `${p.name}<br/>消费: ¥${p.value.toFixed(2)}`;
      },
    },
    grid: { left: 50, right: 20, top: 20, bottom: 60 },
    xAxis: {
      type: 'category',
      data: stats.daily_trend.map((d) => d.date.slice(5)),
      axisLabel: { color: c('text-secondary'), fontSize: 11 },
      axisLine: { lineStyle: { color: c('chart-axis') } },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: c('text-secondary'), fontSize: 11 },
      splitLine: { lineStyle: { color: c('chart-grid') } },
    },
    dataZoom: [{ type: 'inside', start: 0, end: 100 }],
    series: [{
      type: 'line',
      data: stats.daily_trend.map((d) => d.cost),
      smooth: true,
      lineStyle: { color: c('primary'), width: 2 },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: c('chart-area-from') },
          { offset: 1, color: c('chart-area-to') },
        ]),
      },
      itemStyle: { color: c('primary') },
    }],
  };

  const sortedTeams = [...(stats.top_teams || [])].sort((a, b) => (a.cost_consumed || 0) - (b.cost_consumed || 0));
  const teamBarOption: echarts.EChartsCoreOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: c('tooltip-bg'),
      borderColor: c('tooltip-border'),
      textStyle: { color: c('text-primary'), fontSize: 12 },
    },
    grid: { left: 80, right: 40, top: 10, bottom: 20 },
    xAxis: {
      type: 'value',
      axisLabel: { color: c('text-secondary'), fontSize: 11 },
      splitLine: { lineStyle: { color: c('chart-grid') } },
    },
    yAxis: {
      type: 'category',
      data: sortedTeams.map((t) => t.name),
      axisLabel: { color: c('text-secondary'), fontSize: 12 },
      axisLine: { lineStyle: { color: c('chart-axis') } },
    },
    series: [{
      type: 'bar',
      data: sortedTeams.map((t) => t.cost_consumed || 0),
      barWidth: 16,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: c('info') },
          { offset: 1, color: c('accent-2') },
        ]),
        borderRadius: [0, 4, 4, 0],
      },
      label: {
        show: true,
        position: 'right',
        color: c('text-secondary'),
        fontSize: 11,
        formatter: (p: { value: number }) => `¥${p.value.toFixed(2)}`,
      },
    }],
  };

  const sortedUsers = [...stats.top_users].sort((a, b) => (a.cost_consumed || 0) - (b.cost_consumed || 0));
  const barOption: echarts.EChartsCoreOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: c('tooltip-bg'),
      borderColor: c('tooltip-border'),
      textStyle: { color: c('text-primary'), fontSize: 12 },
    },
    grid: { left: 80, right: 40, top: 10, bottom: 20 },
    xAxis: {
      type: 'value',
      axisLabel: { color: c('text-secondary'), fontSize: 11 },
      splitLine: { lineStyle: { color: c('chart-grid') } },
    },
    yAxis: {
      type: 'category',
      data: sortedUsers.map((u) => u.username),
      axisLabel: { color: c('text-secondary'), fontSize: 12 },
      axisLine: { lineStyle: { color: c('chart-axis') } },
    },
    series: [{
      type: 'bar',
      data: sortedUsers.map((u) => u.cost_consumed || 0),
      barWidth: 16,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: c('primary') },
          { offset: 1, color: c('primary-2') },
        ]),
        borderRadius: [0, 4, 4, 0],
      },
      label: {
        show: true,
        position: 'right',
        color: c('text-secondary'),
        fontSize: 11,
        formatter: (p: { value: number }) => `¥${p.value.toFixed(2)}`,
      },
    }],
  };

  return (
    <div className={styles.page}>
      <h1 className={styles.title}>仪表盘</h1>

      <div className={styles.statsGrid}>
        {statCards.map((card) => (
          <div key={card.label} className={styles.statCard}>
            <div className={styles.statLabel}>{card.label}</div>
            <div className={styles.statValue}>{card.value}</div>
            {card.change !== null && (
              <div className={`${styles.statChange} ${card.change >= 0 ? styles.positive : styles.negative}`}>
                <span>{card.change >= 0 ? '↑' : '↓'}</span>
                <span>{Math.abs(card.change)}%</span>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Row 2: Profit cards */}
      <div className={styles.statsGrid}>
        <div className={styles.statCard}>
          <div className={styles.statLabel}>总收入</div>
          <div className={styles.statValue}>{`¥${(stats.total_revenue || 0).toFixed(2)}`}</div>
        </div>
        <div className={styles.statCard}>
          <div className={styles.statLabel}>总成本</div>
          <div className={styles.statValue}>{`¥${(stats.total_base_cost || 0).toFixed(2)}`}</div>
        </div>
        <div className={styles.statCard}>
          <div className={styles.statLabel}>总利润</div>
          <div className={styles.statValue}>{`¥${(stats.total_profit || 0).toFixed(2)}`}</div>
        </div>
        <div className={styles.statCard}>
          <div className={styles.statLabel}>利润率</div>
          <div className={styles.statValue}>{`${(stats.profit_margin || 0).toFixed(1)}%`}</div>
        </div>
      </div>

      {/* Row 3: Trend chart (full width) */}
      <div className={styles.chartSection}>
        <h2 className={styles.sectionTitle}>消费趋势（近30天 · 元）</h2>
        <div className={styles.chartWrapper}>
          <ReactEChartsCore key={`trend-${theme}`} echarts={echarts} option={trendOption} style={{ height: 320 }} />
        </div>
      </div>

      {/* Row 4: Team + User ranking (two columns) */}
      <div className={styles.chartsRow}>
        {sortedTeams.length > 0 && (
          <div className={styles.chartSection}>
            <h2 className={styles.sectionTitle}>团队消费排行（本月）</h2>
            <div className={styles.chartWrapper}>
              <ReactEChartsCore key={`teams-${theme}`} echarts={echarts} option={teamBarOption} style={{ height: Math.max(300, sortedTeams.length * 36) }} />
            </div>
          </div>
        )}

        <div className={styles.chartSection}>
          <h2 className={styles.sectionTitle}>用户消费排行（Top 10 · 本月）</h2>
          <div className={styles.chartWrapper}>
            <ReactEChartsCore key={`users-${theme}`} echarts={echarts} option={barOption} style={{ height: Math.max(300, sortedUsers.length * 36) }} />
          </div>
        </div>
      </div>
    </div>
  );
}
