import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Row,
  Col,
  Statistic,
  Select,
  DatePicker,
  Tabs,
  Badge,
  message,
  Segmented,
} from 'antd';
import {
  SyncOutlined,
  ReloadOutlined,
  AppstoreOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { orderDataSource, OrderDetailData } from '@/services/orderDataSource';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

interface AggregatedOrder {
  id: string;
  platformOrderId: string;
  platform: 'AMAZON' | 'EBAY' | 'SHOPIFY' | 'SHOPEE' | 'LAZADA';
  customerName: string;
  totalAmount: number;
  currency: string;
  status: string;
  createdAt: string;
  shopId: string;
  shopName: string;
}

const PLATFORM_MAP: Record<string, { color: string; text: string }> = {
  AMAZON: { color: 'orange', text: 'Amazon' },
  EBAY: { color: 'blue', text: 'eBay' },
  SHOPIFY: { color: 'green', text: 'Shopify' },
  SHOPEE: { color: 'red', text: 'Shopee' },
  LAZADA: { color: 'purple', text: 'Lazada' },
};

export const OrderAggregation: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState<AggregatedOrder[]>([]);
  const [viewMode, setViewMode] = useState<string>('table');
  const [selectedPlatform, setSelectedPlatform] = useState<string>('all');
  const [stats, setStats] = useState({
    total: 0,
    amazon: 0,
    ebay: 0,
    shopify: 0,
    shopee: 0,
    lazada: 0,
  });

  useEffect(() => {
    fetchAggregatedOrders();
  }, [selectedPlatform]);

  const fetchAggregatedOrders = async () => {
    setLoading(true);
    try {
      const mockOrders: AggregatedOrder[] = [
        { id: '1', platformOrderId: 'AMZ-123456', platform: 'AMAZON', customerName: 'John Smith', totalAmount: 159.99, currency: 'USD', status: 'SHIPPED', createdAt: '2026-03-18 10:30:00', shopId: 'SHOP_001', shopName: 'US Store' },
        { id: '2', platformOrderId: 'EB-789012', platform: 'EBAY', customerName: 'Emma Wilson', totalAmount: 89.50, currency: 'USD', status: 'PENDING', createdAt: '2026-03-18 09:15:00', shopId: 'SHOP_002', shopName: 'eBay Outlet' },
        { id: '3', platformOrderId: 'SH-345678', platform: 'SHOPIFY', customerName: 'Michael Brown', totalAmount: 245.00, currency: 'USD', status: 'PROCESSING', createdAt: '2026-03-17 16:45:00', shopId: 'SHOP_003', shopName: 'Brand Store' },
        { id: '4', platformOrderId: 'SP-901234', platform: 'SHOPEE', customerName: 'Sarah Davis', totalAmount: 78.00, currency: 'USD', status: 'DELIVERED', createdAt: '2026-03-15 11:20:00', shopId: 'SHOP_004', shopName: 'Shopee Mall' },
        { id: '5', platformOrderId: 'LZ-567890', platform: 'LAZADA', customerName: 'David Lee', totalAmount: 120.00, currency: 'USD', status: 'SHIPPED', createdAt: '2026-03-18 08:00:00', shopId: 'SHOP_005', shopName: 'Lazada Seller' },
        { id: '6', platformOrderId: 'AMZ-234567', platform: 'AMAZON', customerName: 'Lisa Chen', totalAmount: 320.00, currency: 'USD', status: 'PENDING', createdAt: '2026-03-18 12:00:00', shopId: 'SHOP_001', shopName: 'US Store' },
        { id: '7', platformOrderId: 'EB-890123', platform: 'EBAY', customerName: 'Tom Wilson', totalAmount: 55.00, currency: 'USD', status: 'DELIVERED', createdAt: '2026-03-14 15:30:00', shopId: 'SHOP_002', shopName: 'eBay Outlet' },
        { id: '8', platformOrderId: 'SH-456789', platform: 'SHOPIFY', customerName: 'Amy Zhang', totalAmount: 199.99, currency: 'USD', status: 'SHIPPED', createdAt: '2026-03-16 14:00:00', shopId: 'SHOP_003', shopName: 'Brand Store' },
      ];

      const filtered = selectedPlatform === 'all'
        ? mockOrders
        : mockOrders.filter((o) => o.platform === selectedPlatform);

      setOrders(filtered);
      calculateStats(mockOrders);
    } catch (error) {
      message.error('Failed to load aggregated orders');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (orderList: AggregatedOrder[]) => {
    setStats({
      total: orderList.length,
      amazon: orderList.filter((o) => o.platform === 'AMAZON').length,
      ebay: orderList.filter((o) => o.platform === 'EBAY').length,
      shopify: orderList.filter((o) => o.platform === 'SHOPIFY').length,
      shopee: orderList.filter((o) => o.platform === 'SHOPEE').length,
      lazada: orderList.filter((o) => o.platform === 'LAZADA').length,
    });
  };

  const columns: ColumnsType<AggregatedOrder> = [
    {
      title: 'Platform Order ID',
      dataIndex: 'platformOrderId',
      key: 'platformOrderId',
      width: 150,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
      render: (platform: string) => {
        const config = PLATFORM_MAP[platform];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Shop',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 120,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 140,
    },
    {
      title: 'Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 100,
      render: (amount: number) => <strong>${amount.toFixed(2)}</strong>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const colorMap: Record<string, string> = {
          PENDING: 'warning',
          PROCESSING: 'processing',
          SHIPPED: 'blue',
          DELIVERED: 'success',
        };
        return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
      },
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
  ];

  return (
    <div className="order-aggregation-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="Total Orders"
              value={stats.total}
              prefix={<AppstoreOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Amazon"
              value={stats.amazon}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<Badge color="#fa8c16" />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="eBay"
              value={stats.ebay}
              valueStyle={{ color: '#1890ff' }}
              prefix={<Badge color="#1890ff" />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Shopify"
              value={stats.shopify}
              valueStyle={{ color: '#52c41a' }}
              prefix={<Badge color="#52c41a" />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Shopee"
              value={stats.shopee}
              valueStyle={{ color: '#f5222d' }}
              prefix={<Badge color="#f5222d" />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Lazada"
              value={stats.lazada}
              valueStyle={{ color: '#722ed1' }}
              prefix={<Badge color="#722ed1" />}
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="Multi-Platform Order Aggregation"
        extra={
          <Space>
            <Select
              value={selectedPlatform}
              onChange={setSelectedPlatform}
              style={{ width: 120 }}
            >
              <Option value="all">All Platforms</Option>
              <Option value="AMAZON">Amazon</Option>
              <Option value="EBAY">eBay</Option>
              <Option value="SHOPIFY">Shopify</Option>
              <Option value="SHOPEE">Shopee</Option>
              <Option value="LAZADA">Lazada</Option>
            </Select>
            <Button icon={<ReloadOutlined />} onClick={fetchAggregatedOrders}>
              Refresh
            </Button>
          </Space>
        }
      >
        <Tabs defaultActiveKey="table">
          <TabPane
            tab={
              <span>
                <UnorderedListOutlined /> Table View
              </span>
            }
            key="table"
          >
            <Table
              columns={columns}
              dataSource={orders}
              rowKey="id"
              loading={loading}
              scroll={{ x: 900 }}
              pagination={{
                showSizeChanger: true,
                showTotal: (total) => `Total ${total} orders`,
              }}
            />
          </TabPane>
          <TabPane
            tab={
              <span>
                <AppstoreOutlined /> Platform Summary
              </span>
            }
            key="summary"
          >
            <Row gutter={[16, 16]}>
              {Object.entries(PLATFORM_MAP).map(([key, config]) => {
                const platformOrders = orders.filter((o) => o.platform === key);
                const totalAmount = platformOrders.reduce((sum, o) => sum + o.totalAmount, 0);
                return (
                  <Col span={8} key={key}>
                    <Card
                      title={<Tag color={config.color}>{config.text}</Tag>}
                      hoverable
                      style={{ cursor: 'pointer' }}
                      onClick={() => setSelectedPlatform(key)}
                    >
                      <Row>
                        <Col span={12}>
                          <Statistic
                            title="Orders"
                            value={platformOrders.length}
                          />
                        </Col>
                        <Col span={12}>
                          <Statistic
                            title="Revenue"
                            value={totalAmount}
                            precision={2}
                            prefix="$"
                          />
                        </Col>
                      </Row>
                    </Card>
                  </Col>
                );
              })}
            </Row>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default OrderAggregation;
