import {
  useState,
  useEffect,
  Card,
  Typography,
  Row,
  Col,
  Button,
  Statistic,
  Space,
  Tabs,
  FileTextOutlined,
  AlertOutlined,
  BarChartOutlined,
  SyncOutlined,
  PlusOutlined,
  SearchOutlined,
  FilterOutlined,
  DollarOutlined,
  TruckOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  Link,
  Area,
  Pie,
  Column,
  orderDataSource,
  Title,
  Text,
  Paragraph,
  FC,
} from '@/imports';
import moment from 'moment';

const OrderManagement: FC = () => {
  const [loading, setLoading] = useState(false);
  const [orderData, setOrderData] = useState<{
    trend: Array<{ date: string; orders: number; amount: number }>;
    platform: Array<{ name: string; value: number }>;
    status: Array<{ name: string; value: number; color: string }>;
    metrics: {
      totalOrders: number;
      totalAmount: number;
      pendingOrders: number;
      todayOrders: number;
      todayAmount: number;
      avgOrderValue: number;
    };
    recentOrders: Array<{ id: string; customer: string; amount: number; status: string; platform: string }>;
  }>({
    trend: [],
    platform: [],
    status: [],
    metrics: {
      totalOrders: 0,
      totalAmount: 0,
      pendingOrders: 0,
      todayOrders: 0,
      todayAmount: 0,
      avgOrderValue: 0,
    },
    recentOrders: [],
  });

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

  const fetchOrderData = async () => {
    setLoading(true);
    try {
      const [trend, platform, status, metrics, recentOrders] = await Promise.all([
        orderDataSource.getOrderTrend(7),
        orderDataSource.getPlatformDistribution(),
        orderDataSource.getStatusDistribution(),
        orderDataSource.getKeyMetrics(),
        orderDataSource.getRecentOrders(4),
      ]);

      setOrderData({
        trend,
        platform,
        status,
        metrics,
        recentOrders,
      });
    } catch (error) {
      console.error('Failed to fetch order data:', error);
    } finally {
      setLoading(false);
    }
  };

  // 配置图表
  const trendConfig = {
    data: orderData.trend,
    xField: 'date',
    yField: 'amount',
    seriesField: 'category',
    yAxis: {
      title: {
        text: '订单金额 (USD)',
      },
    },
    areaStyle: {
      fill: 'l(270) 0:#ffffff 0.5:#1890ff 1:#1890ff',
    },
  };

  const platformConfig = {
    data: orderData.platform,
    angleField: 'value',
    colorField: 'name',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name}: {percentage}',
    },
  };

  const statusConfig = {
    data: orderData.status,
    xField: 'name',
    yField: 'value',
    colorField: 'name',
    color: orderData.status.map(item => item.color),
    label: {
      position: 'top',
    },
  };

  return (
    <div style={{ padding: '0 24px 24px' }}>
      {/* 页面标题和操作区 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, marginTop: 16 }}>
        <div>
          <Title level={4}>订单管理</Title>
          <Text type="secondary">管理和分析所有订单</Text>
        </div>
        <Space>
          <Button icon={<SearchOutlined />}>
            <Link to="/Orders/OrderList">高级搜索</Link>
          </Button>
          <Button icon={<FilterOutlined />}>
            <Link to="/Orders/OrderList">筛选订单</Link>
          </Button>
          <Button type="primary" icon={<SyncOutlined />} loading={loading} onClick={fetchOrderData}>
            刷新数据
          </Button>
        </Space>
      </div>

      {/* 关键指标卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card hoverable>
            <Statistic 
              title="总订单数" 
              value={orderData.metrics.totalOrders} 
              prefix={<FileTextOutlined />}
              suffix={<Text type="secondary">单</Text>}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card hoverable>
            <Statistic 
              title="总销售额" 
              value={orderData.metrics.totalAmount} 
              prefix={<DollarOutlined />}
              suffix={<Text type="secondary">USD</Text>}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card hoverable>
            <Statistic 
              title="待处理订单" 
              value={orderData.metrics.pendingOrders} 
              prefix={<ClockCircleOutlined />}
              suffix={<Text type="secondary">单</Text>}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card hoverable>
            <Statistic 
              title="今日订单" 
              value={orderData.metrics.todayOrders} 
              prefix={<PlusOutlined />}
              suffix={<Text type="secondary">单</Text>}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={16}>
          <Card title="订单趋势" loading={loading}>
            <Area {...trendConfig} />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="平台分布" loading={loading}>
            <Pie {...platformConfig} />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="订单状态分布" loading={loading}>
            <Column {...statusConfig} />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="最近订单" loading={loading}>
            <div style={{ maxHeight: 300, overflowY: 'auto' }}>
              {orderData.recentOrders.map((order, index) => (
                <div key={order.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: index < orderData.recentOrders.length - 1 ? '1px solid #f0f0f0' : 'none' }}>
                  <div>
                    <Text strong>{order.id}</Text>
                    <div style={{ marginTop: 4 }}>
                      <Text type="secondary">客户: {order.customer}</Text>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <Text strong>${order.amount.toFixed(2)}</Text>
                    <div style={{ marginTop: 4 }}>
                      <Text type="secondary">{order.platform}</Text>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </Col>
      </Row>

      {/* 快速导航 */}
      <Card title="快速导航" style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]}>
          <Col span={8}>
            <Card hoverable onClick={() => window.location.href = '/Orders/OrderList'}>
              <div style={{ textAlign: 'center' }}>
                <FileTextOutlined style={{ fontSize: 32, color: '#1890ff', marginBottom: 8 }} />
                <div>
                  <Text strong>订单列表</Text>
                  <p style={{ color: '#999', marginTop: 4 }}>查看和管理所有订单</p>
                </div>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card hoverable onClick={() => window.location.href = '/Orders/ExceptionOrder'}>
              <div style={{ textAlign: 'center' }}>
                <AlertOutlined style={{ fontSize: 32, color: '#ff4d4f', marginBottom: 8 }} />
                <div>
                  <Text strong>异常订单</Text>
                  <p style={{ color: '#999', marginTop: 4 }}>处理退款和取消订单</p>
                </div>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card hoverable onClick={() => window.location.href = '/Orders/OrderAggregation'}>
              <div style={{ textAlign: 'center' }}>
                <BarChartOutlined style={{ fontSize: 32, color: '#52c41a', marginBottom: 8 }} />
                <div>
                  <Text strong>订单统计</Text>
                  <p style={{ color: '#999', marginTop: 4 }}>分析订单数据和趋势</p>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </Card>

      {/* 订单状态概览 */}
      <Card title="订单状态概览">
        <Tabs 
          defaultActiveKey="all"
          items={[
            { key: 'all', label: '全部', children: (
              <>
                <Paragraph>
                  查看所有订单，包括待处理、已确认、已发货、已完成等状态。
                </Paragraph>
                <Button type="primary" style={{ marginTop: 16 }}>
                  <Link to="/Orders/OrderList">查看全部订单</Link>
                </Button>
              </>
            )},
            { key: 'pending', label: '待处理', children: (
              <>
                <Paragraph>
                  待处理订单需要您的确认，包括新订单和未处理的订单。
                </Paragraph>
                <Button type="primary" style={{ marginTop: 16 }}>
                  <Link to="/Orders/OrderList?status=PENDING">处理待处理订单</Link>
                </Button>
              </>
            )},
            { key: 'shipped', label: '已发货', children: (
              <>
                <Paragraph>
                  已发货订单正在运输中，您可以查看物流信息和预计送达时间。
                </Paragraph>
                <Button type="primary" style={{ marginTop: 16 }}>
                  <Link to="/Orders/OrderList?status=SHIPPED">查看已发货订单</Link>
                </Button>
              </>
            )},
            { key: 'exception', label: '异常', children: (
              <>
                <Paragraph>
                  异常订单包括已取消和退款中的订单，需要您的关注和处理。
                </Paragraph>
                <Button type="primary" style={{ marginTop: 16 }}>
                  <Link to="/Orders/ExceptionOrder">处理异常订单</Link>
                </Button>
              </>
            )},
          ]}
        />
      </Card>
    </div>
  );
};

export default OrderManagement;
