import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Spin, DatePicker } from 'antd';
import {
  ArrowUpOutlined,
  ShopOutlined,
  TeamOutlined,
  DollarOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { getPlatformStatistics, getOrderTrend } from '@/api/admin';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<any>({
    merchantCount: 0,
    userCount: 0,
    todayOrders: 0,
    platformBalance: 0,
    merchantTotalBalance: 0,
    userTotalBalance: 0,
    todayIncome: 0,
  });
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(7, 'day'),
    dayjs(),
  ]);
  const [trendData, setTrendData] = useState<any>({
    dates: [],
    orders: [],
    income: [],
  });

  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const res: any = await getPlatformStatistics();
      setStats(res.data || {});

      // 获取趋势数据
      const startDate = dateRange[0].format('YYYY-MM-DD');
      const endDate = dateRange[1].format('YYYY-MM-DD');
      const trendRes: any = await getOrderTrend({ startDate, endDate });

      const trendList = trendRes.data || [];
      const dates = trendList.map((item: any) => dayjs(item.date).format('MM-DD'));
      const income = trendList.map((item: any) => Number(item.income || 0).toFixed(2));
      const orders = trendList.map((item: any) => item.orderCount || 0);

      setTrendData({ dates, orders, income });
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatistics();

    // 设置自动刷新（每5分钟）
    const interval = setInterval(() => {
      fetchStatistics();
    }, 5 * 60 * 1000);

    return () => clearInterval(interval);
  }, [dateRange]);

  // 订单趋势图表配置
  const orderTrendOption = {
    title: {
      text: '订单趋势（近7天）',
      left: 'center',
      textStyle: {
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: trendData.dates,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      name: '订单数',
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        data: trendData.orders,
        smooth: true,
        itemStyle: {
          color: '#1890ff',
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
            ],
          },
        },
      },
    ],
  };

  // 收入趋势图表配置
  const incomeTrendOption = {
    title: {
      text: '收入趋势（近7天）',
      left: 'center',
      textStyle: {
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const item = params[0];
        return `${item.name}<br/>${item.seriesName}: ¥${item.value}`;
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: trendData.dates,
    },
    yAxis: {
      type: 'value',
      name: '收入（元）',
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: trendData.income,
        itemStyle: {
          color: '#52c41a',
        },
      },
    ],
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h2 style={{ margin: 0 }}>数据概览</h2>
        <span style={{ color: '#999', fontSize: 14 }}>
          数据每5分钟自动刷新 · 最后更新: {dayjs().format('HH:mm:ss')}
        </span>
      </div>

      <Row gutter={[24, 24]}>
        <Col span={6}>
          <Card>
            <Statistic title="商家总数" value={stats.merchantCount} prefix={<ShopOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="用户总数" value={stats.userCount} prefix={<TeamOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="今日订单" value={stats.todayOrders} prefix={<UnorderedListOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日收入"
              value={stats.todayIncome}
              prefix={<DollarOutlined />}
              suffix="元"
              precision={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="平台钱包余额"
              value={stats.platformBalance}
              prefix={<DollarOutlined />}
              suffix="元"
              precision={2}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="商家账户总余额"
              value={stats.merchantTotalBalance || 0}
              prefix={<DollarOutlined />}
              suffix="元"
              precision={2}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="用户账户总余额"
              value={stats.userTotalBalance || 0}
              prefix={<DollarOutlined />}
              suffix="元"
              precision={2}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
        <Col span={12}>
          <Card>
            <ReactECharts option={orderTrendOption} style={{ height: 350 }} />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <ReactECharts option={incomeTrendOption} style={{ height: 350 }} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;
