import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Tag,
  Progress,
  Timeline,
  Badge,
  Button,
  List,
  Avatar,
  Typography,
  Space,
  Tabs,
  Alert,
  DatePicker,
  Select,
  Tooltip,
  Empty,
} from 'antd';
import {
  ShoppingOutlined,
  FileTextOutlined,
  DollarOutlined,
  UserOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  RiseOutlined,
  FallOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  CalendarOutlined,
  FilterOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { Line, Pie, Column } from '@ant-design/plots';
import moment from 'moment';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 统计数据接口
interface DashboardStats {
  totalProducts: number;
  productGrowth: number;
  totalOrders: number;
  orderGrowth: number;
  totalRevenue: number;
  revenueGrowth: number;
  totalCustomers: number;
  customerGrowth: number;
  pendingOrders: number;
  processingOrders: number;
  completedOrders: number;
  returnOrders: number;
  lowStockProducts: number;
  expiringCertificates: number;
  activeTasks: number;
  failedTasks: number;
}

// 销售趋势数据
interface SalesTrend {
  date: string;
  sales: number;
  orders: number;
  profit: number;
}

// 平台分布数据
interface PlatformDistribution {
  platform: string;
  value: number;
  color: string;
}

// 最近订单
interface RecentOrder {
  id: string;
  orderId: string;
  platform: string;
  customer: string;
  amount: number;
  status: 'PENDING' | 'CONFIRMED' | 'SHIPPED' | 'DELIVERED' | 'CANCELLED';
  createdAt: string;
}

// 最近活动
interface RecentActivity {
  id: string;
  type: 'ORDER' | 'PRODUCT' | 'SYSTEM' | 'TASK';
  title: string;
  description: string;
  timestamp: string;
  user: string;
}

// 热门产品
interface TopProduct {
  id: string;
  name: string;
  sales: number;
  revenue: number;
  growth: number;
}

// 告警信息
interface Alert {
  id: string;
  type: 'WARNING' | 'ERROR' | 'INFO';
  title: string;
  message: string;
  timestamp: string;
}

const MOCK_STATS: DashboardStats = {
  totalProducts: 1280,
  productGrowth: 12.5,
  totalOrders: 960,
  orderGrowth: 8.3,
  totalRevenue: 1280000,
  revenueGrowth: 15.2,
  totalCustomers: 320,
  customerGrowth: 5.7,
  pendingOrders: 45,
  processingOrders: 128,
  completedOrders: 756,
  returnOrders: 31,
  lowStockProducts: 23,
  expiringCertificates: 5,
  activeTasks: 12,
  failedTasks: 3,
};

const MOCK_SALES_TREND: SalesTrend[] = [
  { date: '2026-03-12', sales: 45000, orders: 45, profit: 12000 },
  { date: '2026-03-13', sales: 52000, orders: 52, profit: 15000 },
  { date: '2026-03-14', sales: 48000, orders: 48, profit: 13500 },
  { date: '2026-03-15', sales: 61000, orders: 61, profit: 18000 },
  { date: '2026-03-16', sales: 55000, orders: 55, profit: 16000 },
  { date: '2026-03-17', sales: 67000, orders: 67, profit: 20000 },
  { date: '2026-03-18', sales: 72000, orders: 72, profit: 22000 },
];

const MOCK_PLATFORM_DISTRIBUTION: PlatformDistribution[] = [
  { platform: 'Amazon', value: 45, color: '#FF9900' },
  { platform: 'eBay', value: 25, color: '#E53238' },
  { platform: 'AliExpress', value: 20, color: '#FF6A00' },
  { platform: 'Shopee', value: 10, color: '#EE4D2D' },
];

const MOCK_RECENT_ORDERS: RecentOrder[] = [
  { id: '1', orderId: 'ORD-2026-001', platform: 'Amazon', customer: 'John Doe', amount: 299.99, status: 'PENDING', createdAt: '2026-03-18 10:30:00' },
  { id: '2', orderId: 'ORD-2026-002', platform: 'eBay', customer: 'Jane Smith', amount: 159.50, status: 'CONFIRMED', createdAt: '2026-03-18 09:15:00' },
  { id: '3', orderId: 'ORD-2026-003', platform: 'AliExpress', customer: 'Bob Johnson', amount: 89.99, status: 'SHIPPED', createdAt: '2026-03-18 08:45:00' },
  { id: '4', orderId: 'ORD-2026-004', platform: 'Amazon', customer: 'Alice Brown', amount: 449.00, status: 'DELIVERED', createdAt: '2026-03-17 16:20:00' },
  { id: '5', orderId: 'ORD-2026-005', platform: 'Shopee', customer: 'Charlie Wilson', amount: 199.99, status: 'PENDING', createdAt: '2026-03-17 14:10:00' },
];

const MOCK_ACTIVITIES: RecentActivity[] = [
  { id: '1', type: 'ORDER', title: '新订单', description: '收到新订单 ORD-2026-001', timestamp: '2026-03-18 10:30:00', user: 'system' },
  { id: '2', type: 'PRODUCT', title: '产品更新', description: '产品 P001 价格已更新', timestamp: '2026-03-18 09:45:00', user: 'admin' },
  { id: '3', type: 'SYSTEM', title: '系统同步', description: 'Amazon 店铺数据同步完成', timestamp: '2026-03-18 09:00:00', user: 'system' },
  { id: '4', type: 'TASK', title: '任务完成', description: '库存检查任务已完成', timestamp: '2026-03-18 08:30:00', user: 'system' },
  { id: '5', type: 'ORDER', title: '订单发货', description: '订单 ORD-2026-003 已发货', timestamp: '2026-03-18 08:15:00', user: 'operator' },
];

const MOCK_TOP_PRODUCTS: TopProduct[] = [
  { id: '1', name: '工业温度传感器', sales: 156, revenue: 46744, growth: 23.5 },
  { id: '2', name: 'PLC控制器', sales: 89, revenue: 44500, growth: 15.2 },
  { id: '3', name: '压力变送器', sales: 134, revenue: 33500, growth: -5.3 },
  { id: '4', name: '流量计', sales: 78, revenue: 23400, growth: 8.7 },
  { id: '5', name: '液位传感器', sales: 112, revenue: 22400, growth: 12.1 },
];

const MOCK_ALERTS: Alert[] = [
  { id: '1', type: 'WARNING', title: '库存不足', message: '23个产品库存低于安全线', timestamp: '2026-03-18 10:00:00' },
  { id: '2', type: 'ERROR', title: '证书过期', message: '5个证书即将过期或已过期', timestamp: '2026-03-18 09:30:00' },
  { id: '3', type: 'INFO', title: '任务失败', message: '3个任务执行失败，请检查', timestamp: '2026-03-18 09:00:00' },
];

const DashboardPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<DashboardStats>(MOCK_STATS);
  const [dateRange, setDateRange] = useState<[moment.Moment, moment.Moment]>([moment().subtract(7, 'days'), moment()]);
  const [platformFilter, setPlatformFilter] = useState<string>('all');

  const fetchData = async () => {
    setLoading(true);
    await new Promise(resolve => setTimeout(resolve, 500));
    setStats(MOCK_STATS);
    setLoading(false);
  };

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

  // 销售趋势图配置
  const salesChartConfig = {
    data: MOCK_SALES_TREND,
    xField: 'date',
    yField: 'sales',
    seriesField: 'type',
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
    color: '#1890ff',
    point: {
      size: 4,
      shape: 'circle',
    },
    tooltip: {
      formatter: (data: any) => {
        return { name: '销售额', value: `¥${data.sales.toLocaleString()}` };
      },
    },
  };

  // 平台分布图配置
  const platformChartConfig = {
    data: MOCK_PLATFORM_DISTRIBUTION,
    angleField: 'value',
    colorField: 'platform',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [
      {
        type: 'element-active',
      },
    ],
  };

  // 订单状态颜色映射
  const orderStatusMap: Record<string, { color: string; text: string }> = {
    PENDING: { color: 'warning', text: '待处理' },
    CONFIRMED: { color: 'processing', text: '已确认' },
    SHIPPED: { color: 'blue', text: '已发货' },
    DELIVERED: { color: 'success', text: '已送达' },
    CANCELLED: { color: 'error', text: '已取消' },
  };

  // 平台颜色映射
  const platformColorMap: Record<string, string> = {
    Amazon: '#FF9900',
    eBay: '#E53238',
    AliExpress: '#FF6A00',
    Shopee: '#EE4D2D',
  };

  // 活动类型图标
  const activityIconMap: Record<string, { icon: React.ReactNode; color: string }> = {
    ORDER: { icon: <FileTextOutlined />, color: '#1890ff' },
    PRODUCT: { icon: <ShoppingOutlined />, color: '#52c41a' },
    SYSTEM: { icon: <SyncOutlined />, color: '#722ed1' },
    TASK: { icon: <CheckCircleOutlined />, color: '#faad14' },
  };

  // 告警类型配置
  const alertConfigMap: Record<string, { type: 'warning' | 'error' | 'info'; icon: React.ReactNode }> = {
    WARNING: { type: 'warning', icon: <WarningOutlined /> },
    ERROR: { type: 'error', icon: <ExclamationCircleOutlined /> },
    INFO: { type: 'info', icon: <CheckCircleOutlined /> },
  };

  // 表格列定义
  const orderColumns: ColumnsType<RecentOrder> = [
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
      render: (text) => <Text strong>{text}</Text>,
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform) => (
        <Tag color={platformColorMap[platform]}>{platform}</Tag>
      ),
    },
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const config = orderStatusMap[status];
        return <Badge status={config.color as any} text={config.text} />;
      },
    },
    {
      title: '时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
  ];

  const productColumns: ColumnsType<TopProduct> = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
    },
    {
      title: '销售额',
      dataIndex: 'revenue',
      key: 'revenue',
      render: (revenue) => `¥${revenue.toLocaleString()}`,
    },
    {
      title: '增长率',
      dataIndex: 'growth',
      key: 'growth',
      render: (growth) => (
        <Space>
          {growth >= 0 ? (
            <RiseOutlined style={{ color: '#52c41a' }} />
          ) : (
            <FallOutlined style={{ color: '#ff4d4f' }} />
          )}
          <Text style={{ color: growth >= 0 ? '#52c41a' : '#ff4d4f' }}>
            {Math.abs(growth)}%
          </Text>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      {/* 页面标题和筛选 */}
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Title level={4}>数据概览</Title>
          <Text type="secondary">实时监控业务数据和关键指标</Text>
        </Col>
        <Col>
          <Space>
            <RangePicker
              value={dateRange}
              onChange={(dates) => dates && setDateRange(dates as [moment.Moment, moment.Moment])}
            />
            <Select
              value={platformFilter}
              onChange={setPlatformFilter}
              style={{ width: 120 }}
              placeholder="平台筛选"
            >
              <Option value="all">全部平台</Option>
              <Option value="Amazon">Amazon</Option>
              <Option value="eBay">eBay</Option>
              <Option value="AliExpress">AliExpress</Option>
              <Option value="Shopee">Shopee</Option>
            </Select>
            <Button icon={<ReloadOutlined />} onClick={fetchData} loading={loading}>
              刷新
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 告警信息 */}
      {MOCK_ALERTS.length > 0 && (
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col span={24}>
            {MOCK_ALERTS.map(alert => {
              const config = alertConfigMap[alert.type];
              return (
                <Alert
                  key={alert.id}
                  message={alert.title}
                  description={alert.message}
                  type={config.type}
                  showIcon
                  icon={config.icon}
                  style={{ marginBottom: 8 }}
                  closable
                />
              );
            })}
          </Col>
        </Row>
      )}

      {/* 核心指标卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="总商品数"
              value={stats.totalProducts}
              prefix={<ShoppingOutlined />}
              suffix={
                <Text type={stats.productGrowth >= 0 ? 'success' : 'danger'} style={{ fontSize: 14 }}>
                  <Space size={4}>
                    {stats.productGrowth >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                    {Math.abs(stats.productGrowth)}%
                  </Space>
                </Text>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="总订单数"
              value={stats.totalOrders}
              prefix={<FileTextOutlined />}
              suffix={
                <Text type={stats.orderGrowth >= 0 ? 'success' : 'danger'} style={{ fontSize: 14 }}>
                  <Space size={4}>
                    {stats.orderGrowth >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                    {Math.abs(stats.orderGrowth)}%
                  </Space>
                </Text>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="总销售额"
              value={stats.totalRevenue}
              prefix={<DollarOutlined />}
              precision={2}
              suffix={
                <Text type={stats.revenueGrowth >= 0 ? 'success' : 'danger'} style={{ fontSize: 14 }}>
                  <Space size={4}>
                    {stats.revenueGrowth >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                    {Math.abs(stats.revenueGrowth)}%
                  </Space>
                </Text>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="客户数"
              value={stats.totalCustomers}
              prefix={<UserOutlined />}
              suffix={
                <Text type={stats.customerGrowth >= 0 ? 'success' : 'danger'} style={{ fontSize: 14 }}>
                  <Space size={4}>
                    {stats.customerGrowth >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                    {Math.abs(stats.customerGrowth)}%
                  </Space>
                </Text>
              }
            />
          </Card>
        </Col>
      </Row>

      {/* 订单状态统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="待处理订单"
              value={stats.pendingOrders}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
            <Progress percent={Math.round((stats.pendingOrders / stats.totalOrders) * 100)} strokeColor="#faad14" showInfo={false} />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="处理中订单"
              value={stats.processingOrders}
              valueStyle={{ color: '#1890ff' }}
              prefix={<SyncOutlined spin />}
            />
            <Progress percent={Math.round((stats.processingOrders / stats.totalOrders) * 100)} strokeColor="#1890ff" showInfo={false} />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="已完成订单"
              value={stats.completedOrders}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
            <Progress percent={Math.round((stats.completedOrders / stats.totalOrders) * 100)} strokeColor="#52c41a" showInfo={false} />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="退货订单"
              value={stats.returnOrders}
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<WarningOutlined />}
            />
            <Progress percent={Math.round((stats.returnOrders / stats.totalOrders) * 100)} strokeColor="#ff4d4f" showInfo={false} />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={16}>
          <Card
            title={
              <Space>
                <LineChartOutlined />
                销售趋势
              </Space>
            }
            loading={loading}
          >
            <Line {...salesChartConfig} height={300} />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card
            title={
              <Space>
                <PieChartOutlined />
                平台分布
              </Space>
            }
            loading={loading}
          >
            <Pie {...platformChartConfig} height={300} />
          </Card>
        </Col>
      </Row>

      {/* 数据表格区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <FileTextOutlined />
                最近订单
              </Space>
            }
            extra={<Button type="link">查看全部</Button>}
            loading={loading}
          >
            <Table
              columns={orderColumns}
              dataSource={MOCK_RECENT_ORDERS}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <BarChartOutlined />
                热销产品
              </Space>
            }
            extra={<Button type="link">查看全部</Button>}
            loading={loading}
          >
            <Table
              columns={productColumns}
              dataSource={MOCK_TOP_PRODUCTS}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>

      {/* 活动和快捷操作 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <ClockCircleOutlined />
                最近活动
              </Space>
            }
            loading={loading}
          >
            <Timeline mode="left">
              {MOCK_ACTIVITIES.map(activity => {
                const config = activityIconMap[activity.type];
                return (
                  <Timeline.Item
                    key={activity.id}
                    dot={
                      <Avatar
                        size="small"
                        icon={config.icon}
                        style={{ backgroundColor: config.color }}
                      />
                    }
                    label={activity.timestamp}
                  >
                    <Text strong>{activity.title}</Text>
                    <div>
                      <Text type="secondary">{activity.description}</Text>
                    </div>
                    <div>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        操作人: {activity.user}
                      </Text>
                    </div>
                  </Timeline.Item>
                );
              })}
            </Timeline>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <WarningOutlined />
                待办事项
              </Space>
            }
            loading={loading}
          >
            <List>
              <List.Item
                actions={[
                  <Button type="link" size="small">去处理</Button>
                ]}
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<ShoppingOutlined />} style={{ backgroundColor: '#ff4d4f' }} />}
                  title={<Text type="danger">库存不足提醒</Text>}
                  description={`${stats.lowStockProducts}个产品库存低于安全线，需要补货`}
                />
              </List.Item>
              <List.Item
                actions={[
                  <Button type="link" size="small">去处理</Button>
                ]}
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<FileTextOutlined />} style={{ backgroundColor: '#faad14' }} />}
                  title={<Text type="warning">证书过期提醒</Text>}
                  description={`${stats.expiringCertificates}个证书即将过期或已过期`}
                />
              </List.Item>
              <List.Item
                actions={[
                  <Button type="link" size="small">去处理</Button>
                ]}
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<SyncOutlined />} style={{ backgroundColor: '#1890ff' }} />}
                  title="待处理任务"
                  description={`${stats.activeTasks}个任务正在运行，${stats.failedTasks}个任务失败`}
                />
              </List.Item>
              <List.Item
                actions={[
                  <Button type="link" size="small">去处理</Button>
                ]}
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<FileTextOutlined />} style={{ backgroundColor: '#52c41a' }} />}
                  title="新订单待确认"
                  description={`${stats.pendingOrders}个新订单等待确认`}
                />
              </List.Item>
            </List>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default DashboardPage;
