import React, { useState, useEffect } from 'react';
import { Card, Typography, Row, Col, Button, Table, Input, Select, Modal, Form, InputNumber, message, Tag, Space, Popconfirm, Tabs } from 'antd';
import { PlusOutlined, UploadOutlined, EditOutlined, SearchOutlined, FilterOutlined, SyncOutlined, DeleteOutlined, EyeOutlined, GlobalOutlined } from '@ant-design/icons';
import { Link } from 'umi';
import CrossPlatformManage from './CrossPlatformManage';

const { Title, Text } = Typography;

interface Product {
  id: string;
  name: string;
  sku: string;
  price: number;
  cost: number;
  stock: number;
  status: 'draft' | 'published' | 'synced';
  platform: string;
  createdAt: string;
}

const ProductManagement: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const [sortField, setSortField] = useState<string>('');
  const [sortOrder, setSortOrder] = useState<'ascend' | 'descend'>('ascend');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [viewingProduct, setViewingProduct] = useState<Product | null>(null);
  const [isPricingModalVisible, setIsPricingModalVisible] = useState(false);
  const [pricingProduct, setPricingProduct] = useState<Product | null>(null);
  const [activeTab, setActiveTab] = useState('local');
  const [form] = Form.useForm();
  const [pricingForm] = Form.useForm();

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

  const fetchProducts = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/v1/products');
      const data = await response.json();
      setProducts(data.data || []);
    } catch (error) {
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleFilter = (status: string) => {
    setFilterStatus(status);
  };

  const handleSort = (field: string, order: 'ascend' | 'descend') => {
    setSortField(field);
    setSortOrder(order);
  };

  const handleAdd = () => {
    setEditingProduct(null);
    form.resetFields();
    setIsModalVisible(true);
  };

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

  const handleView = (record: Product) => {
    setViewingProduct(record);
    setIsDetailModalVisible(true);
  };

  const handlePricing = (record: Product) => {
    setPricingProduct(record);
    pricingForm.setFieldsValue({
      cost: record.cost,
      price: record.price,
      profit: record.price - record.cost,
      profitMargin: ((record.price - record.cost) / record.price * 100).toFixed(2)
    });
    setIsPricingModalVisible(true);
  };

  const handlePublish = async (record: Product) => {
    try {
      await fetch(`/api/v1/products/${record.id}/publish`, {
        method: 'POST'
      });
      message.success('商品上架成功');
      fetchProducts();
    } catch (error) {
      message.error('商品上架失败');
    }
  };

  const handleSync = async (record: Product) => {
    try {
      await fetch(`/api/v1/products/${record.id}/sync`, {
        method: 'POST'
      });
      message.success('商品同步成功');
      fetchProducts();
    } catch (error) {
      message.error('商品同步失败');
    }
  };

  const handleBatchSync = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要同步的商品');
      return;
    }
    try {
      await fetch('/api/v1/products/batch-sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedRowKeys })
      });
      message.success('批量同步成功');
      fetchProducts();
    } catch (error) {
      message.error('批量同步失败');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await fetch(`/api/v1/products/${id}`, {
        method: 'DELETE'
      });
      message.success('商品删除成功');
      fetchProducts();
    } catch (error) {
      message.error('商品删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingProduct) {
        await fetch(`/api/v1/products/${editingProduct.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(values)
        });
        message.success('商品更新成功');
      } else {
        await fetch('/api/v1/products', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(values)
        });
        message.success('商品创建成功');
      }
      setIsModalVisible(false);
      fetchProducts();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handlePricingChange = () => {
    const cost = pricingForm.getFieldValue('cost');
    const price = pricingForm.getFieldValue('price');
    if (cost && price) {
      pricingForm.setFieldsValue({
        profit: price - cost,
        profitMargin: ((price - cost) / price * 100).toFixed(2)
      });
    }
  };

  const handlePricingModalOk = async () => {
    try {
      const values = await pricingForm.validateFields();
      if (pricingProduct) {
        await fetch(`/api/v1/products/${pricingProduct.id}/pricing`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(values)
        });
        message.success('定价更新成功');
        setIsPricingModalVisible(false);
        fetchProducts();
      }
    } catch (error) {
      message.error('定价更新失败');
    }
  };

  const filteredProducts = products.filter(product => {
    if (searchText && !product.name.toLowerCase().includes(searchText.toLowerCase()) && 
        !product.sku.toLowerCase().includes(searchText.toLowerCase())) {
      return false;
    }
    if (filterStatus && product.status !== filterStatus) {
      return false;
    }
    return true;
  });

  const sortedProducts = [...filteredProducts].sort((a, b) => {
    const field = sortField as keyof Product;
    const aValue = a[field];
    const bValue = b[field];
    
    if (sortOrder === 'ascend') {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });

  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      sorter: true,
      render: (price: number) => `¥${price.toFixed(2)}`
    },
    {
      title: '成本',
      dataIndex: 'cost',
      key: 'cost',
      sorter: true,
      render: (cost: number) => `¥${cost.toFixed(2)}`
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      sorter: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '草稿', value: 'draft' },
        { text: '已定价', value: 'priced' },
        { text: '已上架', value: 'listed' },
        { text: '同步中', value: 'syncing' },
        { text: '已在线', value: 'live' },
        { text: '同步失败', value: 'sync_failed' },
        { text: '已下架', value: 'offline' }
      ],
      render: (status: string) => {
        const colorMap: Record<string, string> = {
          draft: 'default',
          priced: 'processing',
          listed: 'warning',
          syncing: 'processing',
          live: 'success',
          sync_failed: 'error',
          offline: 'default'
        };
        const textMap: Record<string, string> = {
          draft: '草稿',
          priced: '已定价',
          listed: '已上架(本地)',
          syncing: '同步中',
          live: '已在线',
          sync_failed: '同步失败',
          offline: '已下架'
        };
        return <Tag color={colorMap[status]}>{textMap[status]}</Tag>;
      }
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Product) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => handlePricing(record)}
          >
            定价
          </Button>
          {record.status === 'draft' && (
            <Button
              type="link"
              onClick={() => handlePublish(record)}
            >
              上架
            </Button>
          )}
          <Button
            type="link"
            icon={<SyncOutlined />}
            onClick={() => handleSync(record)}
          >
            同步
          </Button>
          <Popconfirm
            title="确定要删除这个商品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>商品管理</Title>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增商品
          </Button>
          <Button icon={<UploadOutlined />}>
            <Link to="/Product/MaterialUpload">素材上传</Link>
          </Button>
          <Button
            icon={<SyncOutlined />}
            onClick={handleBatchSync}
            disabled={selectedRowKeys.length === 0}
          >
            批量同步
          </Button>
        </Space>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ marginBottom: 16 }}>
        <Tabs.TabPane tab="本地商品管理" key="local">
          <Card style={{ marginBottom: 16 }}>
            <Space style={{ width: '100%', marginBottom: 16 }}>
              <Input
                placeholder="搜索商品名称或SKU"
                prefix={<SearchOutlined />}
                style={{ width: 300 }}
                onChange={e => handleSearch(e.target.value)}
                allowClear
              />
              <Select
                placeholder="筛选状态"
                style={{ width: 150 }}
                onChange={handleFilter}
                allowClear
              >
                <Select.Option value="draft">草稿</Select.Option>
                <Select.Option value="published">已发布</Select.Option>
                <Select.Option value="synced">已同步</Select.Option>
              </Select>
              <Select
                placeholder="排序字段"
                style={{ width: 150 }}
                onChange={(value) => handleSort(value, sortOrder)}
                allowClear
              >
                <Select.Option value="name">商品名称</Select.Option>
                <Select.Option value="price">价格</Select.Option>
                <Select.Option value="stock">库存</Select.Option>
                <Select.Option value="createdAt">创建时间</Select.Option>
              </Select>
              <Select
                placeholder="排序方式"
                style={{ width: 120 }}
                onChange={(value) => handleSort(sortField, value)}
                value={sortOrder}
              >
                <Select.Option value="ascend">升序</Select.Option>
                <Select.Option value="descend">降序</Select.Option>
              </Select>
            </Space>
          </Card>

          <Card>
            <Table
              rowKey="id"
              columns={columns}
              dataSource={sortedProducts}
              loading={loading}
              rowSelection={{
                selectedRowKeys,
                onChange: setSelectedRowKeys
              }}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条`
              }}
            />
          </Card>
        </Tabs.TabPane>
        <Tabs.TabPane 
          tab={
            <span>
              <GlobalOutlined />
              跨平台商品管理
            </span>
          } 
          key="crossPlatform"
        >
          <CrossPlatformManage />
        </Tabs.TabPane>
      </Tabs>

      <Modal
        title={editingProduct ? '编辑商品' : '新增商品'}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>
          <Form.Item
            name="sku"
            label="SKU"
            rules={[{ required: true, message: '请输入SKU' }]}
          >
            <Input placeholder="请输入SKU" />
          </Form.Item>
          <Form.Item
            name="price"
            label="价格"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber
              placeholder="请输入价格"
              style={{ width: '100%' }}
              min={0}
              precision={2}
            />
          </Form.Item>
          <Form.Item
            name="cost"
            label="成本"
            rules={[{ required: true, message: '请输入成本' }]}
          >
            <InputNumber
              placeholder="请输入成本"
              style={{ width: '100%' }}
              min={0}
              precision={2}
            />
          </Form.Item>
          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber
              placeholder="请输入库存"
              style={{ width: '100%' }}
              min={0}
            />
          </Form.Item>
          <Form.Item
            name="platform"
            label="平台"
            rules={[{ required: true, message: '请选择平台' }]}
          >
            <Select placeholder="请选择平台">
              <Select.Option value="amazon">Amazon</Select.Option>
              <Select.Option value="ebay">eBay</Select.Option>
              <Select.Option value="shopify">Shopify</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="商品详情"
        visible={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {viewingProduct && (
          <div>
            <Row gutter={16}>
              <Col span={12}>
                <Text strong>商品名称：</Text>
                <div>{viewingProduct.name}</div>
              </Col>
              <Col span={12}>
                <Text strong>SKU：</Text>
                <div>{viewingProduct.sku}</div>
              </Col>
            </Row>
            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={8}>
                <Text strong>价格：</Text>
                <div>¥{viewingProduct.price.toFixed(2)}</div>
              </Col>
              <Col span={8}>
                <Text strong>成本：</Text>
                <div>¥{viewingProduct.cost.toFixed(2)}</div>
              </Col>
              <Col span={8}>
                <Text strong>利润：</Text>
                <div>¥{(viewingProduct.price - viewingProduct.cost).toFixed(2)}</div>
              </Col>
            </Row>
            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={8}>
                <Text strong>库存：</Text>
                <div>{viewingProduct.stock}</div>
              </Col>
              <Col span={8}>
                <Text strong>状态：</Text>
                <div>
                  <Tag color={viewingProduct.status === 'published' ? 'green' : 'default'}>
                    {viewingProduct.status === 'published' ? '已发布' : viewingProduct.status === 'synced' ? '已同步' : '草稿'}
                  </Tag>
                </div>
              </Col>
              <Col span={8}>
                <Text strong>平台：</Text>
                <div>{viewingProduct.platform}</div>
              </Col>
            </Row>
          </div>
        )}
      </Modal>

      <Modal
        title="商品定价"
        visible={isPricingModalVisible}
        onOk={handlePricingModalOk}
        onCancel={() => setIsPricingModalVisible(false)}
        width={600}
      >
        <Form form={pricingForm} layout="vertical">
          <Form.Item
            name="cost"
            label="成本"
            rules={[{ required: true, message: '请输入成本' }]}
          >
            <InputNumber
              placeholder="请输入成本"
              style={{ width: '100%' }}
              min={0}
              precision={2}
              onChange={handlePricingChange}
            />
          </Form.Item>
          <Form.Item
            name="price"
            label="价格"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber
              placeholder="请输入价格"
              style={{ width: '100%' }}
              min={0}
              precision={2}
              onChange={handlePricingChange}
            />
          </Form.Item>
          <Form.Item
            name="profit"
            label="利润"
          >
            <InputNumber
              disabled
              style={{ width: '100%' }}
              precision={2}
            />
          </Form.Item>
          <Form.Item
            name="profitMargin"
            label="利润率（%）"
          >
            <InputNumber
              disabled
              style={{ width: '100%' }}
              precision={2}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductManagement;
