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 { teamApi } from '../lib/api';
import type { TeamInfo, TeamStats } 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 TeamDashboardPage() {
  const [info, setInfo] = useState<(TeamInfo & { daily_member_limit_default: number; member_count: number }) | null>(null);
  const [stats, setStats] = useState<TeamStats | null>(null);
  const [loading, setLoading] = useState(true);
  const theme = useThemeStore((s) => s.theme);

  const fetchData = useCallback(async () => {
    try {
      const [infoRes, statsRes] = await Promise.all([
        teamApi.getInfo(),
        teamApi.getStats(),
      ]);
      setInfo(infoRes.data);
      setStats(statsRes.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, 5].map((i) => <div key={i} className={styles.skeletonCard} />)}
          </div>
          <div className={styles.skeletonChart} />
          <div className={styles.skeletonChart} />
        </div>
      </div>
    );
  }

  if (!info || !stats) return null;

  const fmtMoney = (val: number) => '¥' + (val || 0).toFixed(2);

  const statCards = [
    { label: '余额', value: fmtMoney(info.balance) },
    { label: '累计消费', value: fmtMoney(info.total_spent) },
    { label: '可用余额', value: fmtMoney(info.available_balance) },
    { label: '月消费限额', value: fmtMoney(info.monthly_spending_limit) },
    { label: '本月消费', value: fmtMoney(info.monthly_spent) },
  ];

  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 ?? d.seconds),
      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 sortedMembers = [...stats.member_consumption].sort((a, b) => (a.cost_consumed ?? a.seconds_consumed) - (b.cost_consumed ?? b.seconds_consumed));
  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: sortedMembers.map((m) => m.username),
      axisLabel: { color: c('text-secondary'), fontSize: 12 },
      axisLine: { lineStyle: { color: c('chart-axis') } },
    },
    series: [{
      type: 'bar',
      data: sortedMembers.map((m) => m.cost_consumed ?? m.seconds_consumed),
      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} style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
        {statCards.map((card) => (
          <div key={card.label} className={styles.statCard}>
            <div className={styles.statLabel}>{card.label}</div>
            <div className={styles.statValue}>{card.value}</div>
          </div>
        ))}
      </div>

      <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>

      <div className={styles.chartSection}>
        <h2 className={styles.sectionTitle}>成员消费排行</h2>
        <div className={styles.chartWrapper}>
          <ReactEChartsCore key={`members-${theme}`} echarts={echarts} option={barOption} style={{ height: Math.max(300, sortedMembers.length * 36) }} />
        </div>
      </div>
    </div>
  );
}
