import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Select, DatePicker, Space, Modal, Form, InputNumber, message, Spin } from 'antd';
import { EditOutlined, DollarOutlined, BarChartOutlined, RocketOutlined, UploadOutlined, DownloadOutlined, PlusOutlined } from '@ant-design/icons';
import { Tag } from 'antd';
import { productApi } from '../services/ApiService';

const { Option } = Select;
const { Search } = Input;

const ProductPage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isPriceModalVisible, setIsPriceModalVisible] = useState(false);
  const [isAiPricingModalVisible, setIsAiPricingModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<any>(null);
  const [form] = Form.useForm();
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [totalProducts, setTotalProducts] = useState(0);
  const [totalCost, setTotalCost] = useState(0);
  const [totalRevenue, setTotalRevenue] = useState(0);
  const [totalProfit, setTotalProfit] = useState(0);
  const [averageRoi, setAverageRoi] = useState(0);

  // 加载商品数据
  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = async () => {
    setLoading(true);
    try {
      const response = await productApi.getProducts();
      setProducts(response.data || []);
      calculateSummary(response.data || []);
    } catch (error) {
      console.error('Failed to load products:', error);
      message.error('Failed to load products');
      // 加载失败时使用mock数据
      const mockProducts = [
        {
          id: '1',
          name: 'Wireless Headphones',
          sku: 'WH-123',
          cost: 50,
          price: 129.99,
          profit: 79.99,
          roi: 159.98,
          stock: 150,
          status: 'active',
          category: 'Electronics',
          shop: 'Shop 1',
        },
        {
          id: '2',
          name: 'Bluetooth Speaker',
          sku: 'BS-456',
          cost: 35,
          price: 89.99,
          profit: 54.99,
          roi: 157.11,
          stock: 80,
          status: 'active',
          category: 'Electronics',
          shop: 'Shop 1',
        },
        {
          id: '3',
          name: 'Smart Watch',
          sku: 'SW-789',
          cost: 80,
          price: 199.99,
          profit: 119.99,
          roi: 149.99,
          stock: 50,
          status: 'active',
          category: 'Electronics',
          shop: 'Shop 2',
        },
        {
          id: '4',
          name: 'Fitness Tracker',
          sku: 'FT-321',
          cost: 25,
          price: 69.99,
          profit: 44.99,
          roi: 179.96,
          stock: 200,
          status: 'inactive',
          category: 'Electronics',
          shop: 'Shop 2',
        },
      ];
      setProducts(mockProducts);
      calculateSummary(mockProducts);
    } finally {
      setLoading(false);
    }
  };

  const calculateSummary = (productList: any[]) => {
    if (!productList || productList.length === 0) {
      setTotalProducts(0);
      setTotalCost(0);
      setTotalRevenue(0);
      setTotalProfit(0);
      setAverageRoi(0);
      return;
    }

    const total = productList.length;
    const cost = productList.reduce((sum, product) => sum + product.cost, 0);
    const revenue = productList.reduce((sum, product) => sum + product.price, 0);
    const profit = productList.reduce((sum, product) => sum + product.profit, 0);
    const roi = productList.reduce((sum, product) => sum + product.roi, 0) / total;

    setTotalProducts(total);
    setTotalCost(cost);
    setTotalRevenue(revenue);
    setTotalProfit(profit);
    setAverageRoi(roi);
  };

  const handleEdit = (record: any) => {
    setEditingProduct(record);
    form.setFieldsValue(record);
    setIsEditModalVisible(true);
  };

  const handlePriceChange = (record: any) => {
    setEditingProduct(record);
    form.setFieldsValue({ price: record.price });
    setIsPriceModalVisible(true);
  };

  const [isAiLoading, setIsAiLoading] = useState(false);
  const [aiSuggestedPrice, setAiSuggestedPrice] = useState<number>(0);

  const handleAiPricing = async (record: any) => {
    setEditingProduct(record);
    setIsAiLoading(true);
    
    try {
      // 调用AI定价API
      const response = await productApi.getAiPricing(record.id);
      setAiSuggestedPrice(response.suggestedPrice || record.cost * (2 + Math.random() * 1));
    } catch (error) {
      console.error('Failed to get AI pricing:', error);
      // 失败时使用模拟数据
      const suggestedPrice = record.cost * (2 + Math.random() * 1);
      setAiSuggestedPrice(suggestedPrice);
    } finally {
      setIsAiLoading(false);
      setIsAiPricingModalVisible(true);
    }
  };

  const handleToggleStatus = async (record: any) => {
    try {
      await productApi.toggleStatus(record.id);
      message.success(`${record.name} has been ${record.status === 'active' ? 'deactivated' : 'activated'}`);
      // 重新加载商品数据
      loadProducts();
    } catch (error) {
      console.error('Failed to toggle status:', error);
      message.error('Failed to toggle status');
    }
  };

  const handleBatchPriceChange = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      await productApi.batchUpdate(selectedRowKeys.map(key => key.toString()), { action: 'price' });
      message.success('Batch price change initiated');
      // 重新加载商品数据
      loadProducts();
    } catch (error) {
      console.error('Failed to batch update price:', error);
      message.error('Failed to batch update price');
    }
  };

  const handleBatchActivate = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      await productApi.batchUpdate(selectedRowKeys.map(key => key.toString()), { action: 'activate' });
      message.success('Batch activation initiated');
      // 重新加载商品数据
      loadProducts();
    } catch (error) {
      console.error('Failed to batch activate:', error);
      message.error('Failed to batch activate');
    }
  };

  const handleBatchAnalysis = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      await productApi.batchUpdate(selectedRowKeys.map(key => key.toString()), { action: 'analyze' });
      message.success('Batch analysis initiated');
    } catch (error) {
      console.error('Failed to batch analyze:', error);
      message.error('Failed to batch analyze');
    }
  };

  const handleCreateProduct = () => {
    // 这里可以打开创建商品的表单
    message.success('Create product form opened');
  };

  const handleImportProducts = () => {
    // 这里可以打开导入商品的对话框
    message.success('Import products dialog opened');
  };

  const handleExportProducts = async () => {
    try {
      // 调用导出API
      await productApi.getProducts({ export: true });
      message.success('Products exported');
    } catch (error) {
      console.error('Failed to export products:', error);
      message.error('Failed to export products');
    }
  };

  const columns = [
    {
      title: 'Product Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: 'Cost',
      dataIndex: 'cost',
      key: 'cost',
      render: (value: number) => `¥${value}`,
    },
    {
      title: 'Price',
      dataIndex: 'price',
      key: 'price',
      render: (value: number) => `¥${value}`,
    },
    {
      title: 'Profit',
      dataIndex: 'profit',
      key: 'profit',
      render: (value: number) => `¥${value}`,
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (value: number) => `${value}%`,
    },
    {
      title: 'Stock',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? 'Active' : 'Inactive'}
        </Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EditOutlined />} onClick={() => handleEdit(record)}>Edit</Button>
          <Button icon={<DollarOutlined />} onClick={() => handlePriceChange(record)}>Change Price</Button>
          <Button icon={<BarChartOutlined />}>View ROI</Button>
          <Button icon={<RocketOutlined />} onClick={() => handleAiPricing(record)}>AI Pricing</Button>
          <Button onClick={() => handleToggleStatus(record)}>
            {record.status === 'active' ? 'Deactivate' : 'Activate'}
          </Button>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    },
  };

  return (
    <div className="product-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>Products</h1>
        <Space>
          <Button icon={<PlusOutlined />} onClick={handleCreateProduct}>Create Product</Button>
          <Button icon={<UploadOutlined />} onClick={handleImportProducts}>Import Products</Button>
          <Button icon={<DownloadOutlined />} onClick={handleExportProducts}>Export Data</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
          <Select placeholder="Select Shop" style={{ width: 150 }}>
            <Option value="all">All Shops</Option>
            <Option value="shop1">Shop 1</Option>
            <Option value="shop2">Shop 2</Option>
          </Select>
          <Select placeholder="Select Category" style={{ width: 150 }}>
            <Option value="all">All Categories</Option>
            <Option value="electronics">Electronics</Option>
            <Option value="clothing">Clothing</Option>
            <Option value="home">Home</Option>
          </Select>
          <Select placeholder="Select Status" style={{ width: 150 }}>
            <Option value="all">All Status</Option>
            <Option value="active">Active</Option>
            <Option value="inactive">Inactive</Option>
          </Select>
          <Search placeholder="Search products" style={{ width: 300 }} />
        </div>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button onClick={handleBatchPriceChange} disabled={selectedRowKeys.length === 0}>
              Batch Price Change
            </Button>
            <Button onClick={handleBatchActivate} disabled={selectedRowKeys.length === 0}>
              Batch Activate
            </Button>
            <Button onClick={handleBatchAnalysis} disabled={selectedRowKeys.length === 0}>
              Batch Analysis
            </Button>
          </Space>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={products}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
          }}
        />
      </Card>

      <Card title="Profit Summary" style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-around' }}>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Products</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>{totalProducts}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Cost</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>¥{totalCost.toFixed(2)}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Revenue</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>¥{totalRevenue.toFixed(2)}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Profit</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>¥{totalProfit.toFixed(2)}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Average ROI</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>{averageRoi.toFixed(2)}%</p>
          </div>
        </div>
      </Card>

      <Modal
        title="Edit Product"
        open={isEditModalVisible}
        onCancel={() => setIsEditModalVisible(false)}
        onOk={async () => {
          try {
            const values = await form.validateFields();
            await productApi.updateProduct(editingProduct.id, values);
            setIsEditModalVisible(false);
            message.success('Product updated successfully');
            // 重新加载商品数据
            loadProducts();
          } catch (error) {
            console.error('Failed to update product:', error);
            message.error('Failed to update product');
          }
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="Product Name">
            <Input />
          </Form.Item>
          <Form.Item name="sku" label="SKU">
            <Input />
          </Form.Item>
          <Form.Item name="cost" label="Cost">
            <InputNumber prefix="¥" />
          </Form.Item>
          <Form.Item name="price" label="Price">
            <InputNumber prefix="¥" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Change Price"
        open={isPriceModalVisible}
        onCancel={() => setIsPriceModalVisible(false)}
        onOk={async () => {
          try {
            const newPrice = form.getFieldValue('price');
            if (newPrice) {
              await productApi.updatePrice(editingProduct.id, newPrice);
              setIsPriceModalVisible(false);
              message.success('Price updated successfully');
              // 重新加载商品数据
              loadProducts();
            }
          } catch (error) {
            console.error('Failed to update price:', error);
            message.error('Failed to update price');
          }
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="price" label="New Price">
            <InputNumber 
              prefix="¥" 
              onChange={(value) => {
                if (value && editingProduct) {
                  // 实时计算ROI
                  const newProfit = value - editingProduct.cost;
                  const newRoi = (newProfit / editingProduct.cost) * 100;
                  
                  // 更新ROI显示
                  const roiElement = document.getElementById('estimated-roi');
                  if (roiElement) {
                    roiElement.textContent = `${newRoi.toFixed(2)}%`;
                    roiElement.style.color = newRoi >= 150 ? '#52c41a' : '#faad14';
                  }
                }
              }}
            />
          </Form.Item>
          <div style={{ margin: '16px 0' }}>
            <p>Current Cost: <span style={{ fontWeight: 'bold' }}>¥{editingProduct?.cost}</span></p>
            <p>Estimated Profit: <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
              ¥{(form.getFieldValue('price') - editingProduct?.cost).toFixed(2)}
            </span></p>
            <p>Estimated ROI: <span id="estimated-roi" style={{ fontWeight: 'bold', color: '#52c41a' }}>
              {((form.getFieldValue('price') - editingProduct?.cost) / editingProduct?.cost * 100).toFixed(2)}%
            </span></p>
          </div>
        </Form>
      </Modal>

      <Modal
        title="AI Pricing"
        open={isAiPricingModalVisible}
        onCancel={() => setIsAiPricingModalVisible(false)}
        onOk={async () => {
          try {
            if (editingProduct && aiSuggestedPrice > 0) {
              await productApi.updatePrice(editingProduct.id, aiSuggestedPrice);
              setIsAiPricingModalVisible(false);
              message.success('AI pricing applied successfully');
              // 重新加载商品数据
              loadProducts();
            }
          } catch (error) {
            console.error('Failed to apply AI pricing:', error);
            message.error('Failed to apply AI pricing');
          }
        }}
      >
        {isAiLoading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px 0' }}>
            <div>
              <p>AI is calculating the optimal price...</p>
              <div style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}>
                <Spin size="large" />
              </div>
            </div>
          </div>
        ) : (
          <div style={{ margin: '16px 0' }}>
            <p>Current Price: <span style={{ fontWeight: 'bold' }}>¥{editingProduct?.price}</span></p>
            <p>AI Suggested Price: <span style={{ fontWeight: 'bold', color: '#1890ff' }}>¥{aiSuggestedPrice.toFixed(2)}</span></p>
            <p>Estimated Profit: <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
              ¥{(aiSuggestedPrice - editingProduct?.cost).toFixed(2)}
            </span></p>
            <p>Estimated ROI: <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
              {((aiSuggestedPrice - editingProduct?.cost) / editingProduct?.cost * 100).toFixed(2)}%
            </span></p>
            <div style={{ marginTop: 16, padding: 12, backgroundColor: '#f6ffed', borderRadius: 4 }}>
              <p style={{ margin: 0 }}>AI Pricing Insights:</p>
              <ul style={{ marginTop: 8, marginBottom: 0 }}>
                <li>Market competitive price: ¥{aiSuggestedPrice.toFixed(2)}</li>
                <li>Expected conversion rate: 8.5%</li>
                <li>Recommended pricing strategy: Dynamic pricing</li>
              </ul>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ProductPage;