import React, { useState, useEffect } from 'react';
import {
  Card,
  Tabs,
  Table,
  Tag,
  Statistic,
  Row,
  Col,
  Spin,
  message,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Badge,
  Typography,
  Space,
  Divider,
  Alert,
  Tooltip,
  Progress,
  Drawer,
  Descriptions,
  Timeline,
  Empty
} from 'antd';
import {
  DollarOutlined,
  RiseOutlined,
  FallOutlined,
  SwapOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  StopOutlined,
  SearchOutlined,
  FilterOutlined,
  GlobalOutlined,
  ShoppingCartOutlined,
  ThunderboltOutlined,
  WarningOutlined,
  TrophyOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import arbitrageDataSource, {
  ArbitrageOpportunity,
  ArbitrageStats
} from '@/services/arbitrageDataSource';

const { TabPane } = Tabs;
const { Option } = Select;
const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

const riskColors: Record<string, string> = {
  LOW: 'success',
  MEDIUM: 'warning',
  HIGH: 'error',
  BLOCK: 'default'
};

const statusColors: Record<string, string> = {
  PENDING: 'default',
  APPROVED: 'processing',
  REJECTED: 'error',
  EXECUTING: 'processing',
  EXECUTED: 'success',
  FAILED: 'error'
};

const statusIcons: Record<string, React.ReactNode> = {
  PENDING: <ClockCircleOutlined />,
  APPROVED: <CheckCircleOutlined />,
  REJECTED: <CloseCircleOutlined />,
  EXECUTING: <SyncOutlined spin />,
  EXECUTED: <CheckCircleOutlined />,
  FAILED: <CloseCircleOutlined />
};

const platformColors: Record<string, string> = {
  Amazon: '#ff9900',
  Temu: '#ff6b35',
  TikTok: '#000000',
  Shopee: '#ee4d2d',
  '1688': '#ff6a00',
  eBay: '#e53238'
};

const ArbitrageMonitorPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [opportunities, setOpportunities] = useState<ArbitrageOpportunity[]>([]);
  const [stats, setStats] = useState<ArbitrageStats | null>(null);
  const [selectedOpportunity, setSelectedOpportunity] = useState<ArbitrageOpportunity | null>(null);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [scanModalVisible, setScanModalVisible] = useState(false);
  const [rejectModalVisible, setRejectModalVisible] = useState(false);
  const [rejectReason, setRejectReason] = useState('');
  const [filterStatus, setFilterStatus] = useState<string | undefined>();
  const [filterPlatform, setFilterPlatform] = useState<string | undefined>();
  const [form] = Form.useForm();

  useEffect(() => {
    fetchOpportunities();
    fetchStats();
  }, [filterStatus, filterPlatform]);

  const fetchOpportunities = async () => {
    setLoading(true);
    try {
      const result = await arbitrageDataSource.getOpportunities({
        status: filterStatus,
        platform: filterPlatform
      });
      setOpportunities(result.opportunities || []);
    } catch (error) {
      message.error('Failed to fetch opportunities');
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const data = await arbitrageDataSource.getStats();
      setStats(data);
    } catch (error) {
      console.error('Failed to fetch stats:', error);
    }
  };

  const handleApprove = async (opportunityId: string) => {
    try {
      await arbitrageDataSource.approveOpportunity(opportunityId);
      message.success('Opportunity approved');
      fetchOpportunities();
      fetchStats();
    } catch (error) {
      message.error('Failed to approve opportunity');
    }
  };

  const handleReject = async () => {
    if (!selectedOpportunity) return;

    try {
      await arbitrageDataSource.rejectOpportunity(selectedOpportunity.id, rejectReason);
      message.success('Opportunity rejected');
      setRejectModalVisible(false);
      setRejectReason('');
      setSelectedOpportunity(null);
      fetchOpportunities();
      fetchStats();
    } catch (error) {
      message.error('Failed to reject opportunity');
    }
  };

  const handleExecute = async (opportunityId: string) => {
    try {
      await arbitrageDataSource.executeOpportunity(opportunityId);
      message.success('Execution started');
      fetchOpportunities();
      fetchStats();
    } catch (error) {
      message.error('Failed to execute opportunity');
    }
  };

  const handleScan = async (values: any) => {
    try {
      const newOpportunities = await arbitrageDataSource.scanProducts(values);
      message.success(`Found ${newOpportunities.length} new opportunities`);
      setScanModalVisible(false);
      form.resetFields();
      fetchOpportunities();
      fetchStats();
    } catch (error) {
      message.error('Failed to scan for opportunities');
    }
  };

  const showOpportunityDetail = (opportunity: ArbitrageOpportunity) => {
    setSelectedOpportunity(opportunity);
    setDetailDrawerVisible(true);
  };

  const columns: ColumnsType<ArbitrageOpportunity> = [
    {
      title: 'Product',
      dataIndex: 'product_name',
      key: 'product_name',
      width: 200,
      ellipsis: true,
      render: (name: string, record) => (
        <Space direction="vertical" size="small">
          <Text strong style={{ fontSize: 13 }}>{name}</Text>
          <Text type="secondary" style={{ fontSize: 11 }}>ID: {record.product_id}</Text>
        </Space>
      )
    },
    {
      title: 'Source',
      key: 'source',
      width: 140,
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Tag color={platformColors[record.source_platform] || 'default'}>
            {record.source_platform}
          </Tag>
          <Text type="secondary">
            {record.source_currency} {record.source_price.toFixed(2)}
          </Text>
        </Space>
      )
    },
    {
      title: 'Target',
      key: 'target',
      width: 140,
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Tag color={platformColors[record.target_platform] || 'default'}>
            {record.target_platform}
          </Tag>
          <Text type="secondary">
            {record.target_currency} {record.target_price.toFixed(2)}
          </Text>
        </Space>
      )
    },
    {
      title: 'Profit',
      key: 'profit',
      width: 120,
      render: (_, record) => {
        const profit = record.profit_snapshot?.netProfit || 0;
        const profitRate = record.profit_snapshot?.profitRate || 0;
        return (
          <Space direction="vertical" size="small">
            <Text style={{ color: profit >= 0 ? '#52c41a' : '#ff4d4f', fontWeight: 'bold' }}>
              ${profit.toFixed(2)}
            </Text>
            <Text type="secondary" style={{ fontSize: 11 }}>
              {(profitRate * 100).toFixed(1)}%
            </Text>
          </Space>
        );
      }
    },
    {
      title: 'ROI',
      dataIndex: ['profit_snapshot', 'roi'],
      key: 'roi',
      width: 80,
      render: (roi: number) => (
        <Text style={{ color: roi >= 0.3 ? '#52c41a' : roi >= 0.15 ? '#faad14' : '#ff4d4f' }}>
          {(roi * 100).toFixed(1)}%
        </Text>
      )
    },
    {
      title: 'Score',
      dataIndex: 'opportunity_score',
      key: 'opportunity_score',
      width: 80,
      render: (score: number) => (
        <Progress
          percent={score}
          size="small"
          showInfo={false}
          strokeColor={score >= 70 ? '#52c41a' : score >= 40 ? '#faad14' : '#ff4d4f'}
        />
      )
    },
    {
      title: 'Risk',
      dataIndex: 'risk_level',
      key: 'risk_level',
      width: 80,
      render: (risk: string) => (
        <Tag color={riskColors[risk]}>{risk}</Tag>
      )
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={statusColors[status]} icon={statusIcons[status]}>
          {status}
        </Tag>
      )
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="View Details">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => showOpportunityDetail(record)}
            />
          </Tooltip>
          {record.status === 'PENDING' && (
            <>
              <Tooltip title="Approve">
                <Button
                  type="text"
                  icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                  onClick={() => handleApprove(record.id)}
                />
              </Tooltip>
              <Tooltip title="Reject">
                <Button
                  type="text"
                  icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
                  onClick={() => {
                    setSelectedOpportunity(record);
                    setRejectModalVisible(true);
                  }}
                />
              </Tooltip>
            </>
          )}
          {record.status === 'APPROVED' && (
            <Tooltip title="Execute">
              <Button
                type="text"
                icon={<PlayCircleOutlined style={{ color: '#1890ff' }} />}
                onClick={() => handleExecute(record.id)}
              />
            </Tooltip>
          )}
        </Space>
      )
    }
  ];

  const renderStatsCards = () => (
    <Row gutter={[16, 16]}>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="Total Opportunities"
            value={stats?.totalOpportunities || 0}
            prefix={<SwapOutlined />}
          />
        </Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="Pending Review"
            value={stats?.pendingOpportunities || 0}
            prefix={<ClockCircleOutlined />}
            valueStyle={{ color: '#faad14' }}
          />
        </Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="Total Profit"
            value={stats?.totalProfit || 0}
            prefix={<DollarOutlined />}
            precision={2}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="Success Rate"
            value={(stats?.successRate || 0) * 100}
            suffix="%"
            prefix={<TrophyOutlined />}
            valueStyle={{ color: stats?.successRate && stats.successRate > 0.5 ? '#52c41a' : '#ff4d4f' }}
          />
        </Card>
      </Col>
    </Row>
  );

  const renderOpportunityDetail = () => {
    if (!selectedOpportunity) return null;

    const profit = selectedOpportunity.profit_snapshot;

    return (
      <Drawer
        title={`Opportunity Details - ${selectedOpportunity.product_name}`}
        placement="right"
        width={600}
        onClose={() => setDetailDrawerVisible(false)}
        open={detailDrawerVisible}
      >
        <Descriptions column={2} bordered size="small">
          <Descriptions.Item label="Product ID" span={2}>
            {selectedOpportunity.product_id}
          </Descriptions.Item>
          <Descriptions.Item label="Source Platform">
            <Tag color={platformColors[selectedOpportunity.source_platform]}>
              {selectedOpportunity.source_platform}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Target Platform">
            <Tag color={platformColors[selectedOpportunity.target_platform]}>
              {selectedOpportunity.target_platform}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Source Price">
            {selectedOpportunity.source_currency} {selectedOpportunity.source_price.toFixed(2)}
          </Descriptions.Item>
          <Descriptions.Item label="Target Price">
            {selectedOpportunity.target_currency} {selectedOpportunity.target_price.toFixed(2)}
          </Descriptions.Item>
        </Descriptions>

        <Divider>Profit Analysis</Divider>

        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="Net Profit"
              value={profit?.netProfit || 0}
              prefix="$"
              precision={2}
              valueStyle={{ color: (profit?.netProfit || 0) >= 0 ? '#52c41a' : '#ff4d4f' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="Profit Rate"
              value={(profit?.profitRate || 0) * 100}
              suffix="%"
              precision={1}
              valueStyle={{ color: (profit?.profitRate || 0) >= 0.2 ? '#52c41a' : '#faad14' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="ROI"
              value={(profit?.roi || 0) * 100}
              suffix="%"
              precision={1}
              valueStyle={{ color: (profit?.roi || 0) >= 0.3 ? '#52c41a' : '#faad14' }}
            />
          </Col>
        </Row>

        <Divider>Cost Breakdown</Divider>

        <Descriptions column={2} size="small">
          <Descriptions.Item label="Platform Fee">${profit?.platformFee?.toFixed(2) || '0.00'}</Descriptions.Item>
          <Descriptions.Item label="Logistics Cost">${profit?.logisticsCost?.toFixed(2) || '0.00'}</Descriptions.Item>
          <Descriptions.Item label="Tax Cost">${profit?.taxCost?.toFixed(2) || '0.00'}</Descriptions.Item>
          <Descriptions.Item label="Opportunity Score">{selectedOpportunity.opportunity_score}</Descriptions.Item>
        </Descriptions>

        <Divider>Status</Divider>

        <Space direction="vertical" style={{ width: '100%' }}>
          <Tag color={statusColors[selectedOpportunity.status]} icon={statusIcons[selectedOpportunity.status]}>
            {selectedOpportunity.status}
          </Tag>
          <Tag color={riskColors[selectedOpportunity.risk_level]}>
            Risk: {selectedOpportunity.risk_level}
          </Tag>
          <Text type="secondary">
            Created: {new Date(selectedOpportunity.created_at).toLocaleString()}
          </Text>
        </Space>

        {selectedOpportunity.error_message && (
          <Alert
            type="error"
            message="Error"
            description={selectedOpportunity.error_message}
            style={{ marginTop: 16 }}
          />
        )}

        <Divider>Actions</Divider>

        <Space>
          {selectedOpportunity.status === 'PENDING' && (
            <>
              <Button type="primary" icon={<CheckCircleOutlined />} onClick={() => handleApprove(selectedOpportunity.id)}>
                Approve
              </Button>
              <Button danger icon={<CloseCircleOutlined />} onClick={() => setRejectModalVisible(true)}>
                Reject
              </Button>
            </>
          )}
          {selectedOpportunity.status === 'APPROVED' && (
            <Button type="primary" icon={<PlayCircleOutlined />} onClick={() => handleExecute(selectedOpportunity.id)}>
              Execute Now
            </Button>
          )}
        </Space>
      </Drawer>
    );
  };

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

  return (
    <div style={{ padding: 24 }}>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card>
            <Row gutter={16} align="middle">
              <Col flex="auto">
                <Title level={3} style={{ margin: 0 }}>
                  <SwapOutlined /> Arbitrage Monitor
                </Title>
                <Text type="secondary">
                  Cross-platform arbitrage opportunity discovery and execution
                </Text>
              </Col>
              <Col>
                <Space>
                  <Select
                    placeholder="Filter Status"
                    allowClear
                    style={{ width: 120 }}
                    onChange={setFilterStatus}
                    value={filterStatus}
                  >
                    <Option value="PENDING">Pending</Option>
                    <Option value="APPROVED">Approved</Option>
                    <Option value="EXECUTED">Executed</Option>
                    <Option value="FAILED">Failed</Option>
                  </Select>
                  <Select
                    placeholder="Filter Platform"
                    allowClear
                    style={{ width: 120 }}
                    onChange={setFilterPlatform}
                    value={filterPlatform}
                  >
                    <Option value="Amazon">Amazon</Option>
                    <Option value="Temu">Temu</Option>
                    <Option value="TikTok">TikTok</Option>
                    <Option value="Shopee">Shopee</Option>
                  </Select>
                  <Button type="primary" icon={<SearchOutlined />} onClick={() => setScanModalVisible(true)}>
                    Scan Products
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col span={24}>
          {renderStatsCards()}
        </Col>

        <Col span={24}>
          <Card>
            <Tabs defaultActiveKey="opportunities">
              <TabPane tab={<span><SwapOutlined /> Opportunities</span>} key="opportunities">
                <Table
                  columns={columns}
                  dataSource={opportunities}
                  rowKey="id"
                  pagination={{ pageSize: 20 }}
                  scroll={{ x: 1200 }}
                  locale={{
                    emptyText: (
                      <Empty
                        description="No arbitrage opportunities found"
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                      >
                        <Button type="primary" onClick={() => setScanModalVisible(true)}>
                          Scan for Opportunities
                        </Button>
                      </Empty>
                    )
                  }}
                />
              </TabPane>
              <TabPane tab={<span><ThunderboltOutlined /> Best Opportunities</span>} key="best">
                <Table
                  columns={columns}
                  dataSource={opportunities.filter(o => o.opportunity_score >= 70 && o.status === 'PENDING')}
                  rowKey="id"
                  pagination={false}
                  scroll={{ x: 1200 }}
                />
              </TabPane>
              <TabPane tab={<span><GlobalOutlined /> By Platform</span>} key="platforms">
                {stats?.byPlatform && Object.keys(stats.byPlatform).length > 0 ? (
                  <Row gutter={[16, 16]}>
                    {Object.entries(stats.byPlatform).map(([platform, data]) => (
                      <Col span={6} key={platform}>
                        <Card size="small">
                          <Statistic
                            title={<Tag color={platformColors[platform]}>{platform}</Tag>}
                            value={data.count}
                            suffix="opportunities"
                          />
                          <Divider style={{ margin: '12px 0' }} />
                          <Text type="secondary">Total Profit: </Text>
                          <Text strong style={{ color: '#52c41a' }}>${data.profit.toFixed(2)}</Text>
                        </Card>
                      </Col>
                    ))}
                  </Row>
                ) : (
                  <Empty description="No platform data available" />
                )}
              </TabPane>
            </Tabs>
          </Card>
        </Col>
      </Row>

      {renderOpportunityDetail()}

      <Modal
        title="Scan for Arbitrage Opportunities"
        open={scanModalVisible}
        onCancel={() => setScanModalVisible(false)}
        onOk={() => form.submit()}
        width={500}
      >
        <Form form={form} layout="vertical" onFinish={handleScan}>
          <Form.Item name="productIds" label="Product IDs" rules={[{ required: true }]}>
            <TextArea
              rows={4}
              placeholder="Enter product IDs, one per line"
            />
          </Form.Item>
          <Form.Item name="sourcePlatform" label="Source Platform" initialValue="1688">
            <Select>
              <Option value="1688">1688</Option>
              <Option value="Alibaba">Alibaba</Option>
              <Option value="Taobao">Taobao</Option>
            </Select>
          </Form.Item>
          <Alert
            message="Note"
            description="The system will scan all target platforms for each product and identify profitable arbitrage opportunities."
            type="info"
            showIcon
          />
        </Form>
      </Modal>

      <Modal
        title="Reject Opportunity"
        open={rejectModalVisible}
        onCancel={() => {
          setRejectModalVisible(false);
          setRejectReason('');
        }}
        onOk={handleReject}
        okText="Reject"
        okButtonProps={{ danger: true }}
      >
        <Form.Item label="Rejection Reason">
          <TextArea
            rows={4}
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
            placeholder="Enter the reason for rejection..."
          />
        </Form.Item>
      </Modal>
    </div>
  );
};

export default ArbitrageMonitorPage;
