import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, message, Upload, Modal, Form } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { independentSiteDataSource, SiteProduct } from '@/services/independentSiteDataSource';

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

interface Product {
  id: string;
  name: string;
  sku: string;
  price: number;
  stock: number;
  status: 'published' | 'draft' | 'unpublished';
  createdAt: string;
  lastUpdated: string;
}

const IndependentSiteProduct: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: '',
    search: '',
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();

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

  const fetchProducts = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      const mockProducts: Product[] = [
        {
          id: '1',
          name: 'Test Product 1',
          sku: 'TP-001',
          price: 99.99,
          stock: 100,
          status: 'published',
          createdAt: '2026-03-01',
          lastUpdated: '2026-03-15',
        },
        {
          id: '2',
          name: 'Test Product 2',
          sku: 'TP-002',
          price: 199.99,
          stock: 50,
          status: 'draft',
          createdAt: '2026-03-05',
          lastUpdated: '2026-03-10',
        },
        {
          id: '3',
          name: 'Test Product 3',
          sku: 'TP-003',
          price: 299.99,
          stock: 25,
          status: 'unpublished',
          createdAt: '2026-03-10',
          lastUpdated: '2026-03-18',
        },
      ];
      setProducts(mockProducts);
      setLoading(false);
    }, 500);
  };

  const handleAddProduct = () => {
    form.resetFields();
    setModalVisible(true);
  };

  const handleEditProduct = (record: Product) => {
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDeleteProduct = (id: string) => {
    message.success('商品已删除');
    fetchProducts();
  };

  const handlePublishProduct = (id: string) => {
    message.success('商品已发布');
    fetchProducts();
  };

  const handleUnpublishProduct = (id: string) => {
    message.success('商品已下架');
    fetchProducts();
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      message.success('商品保存成功');
      setLoading(false);
      setModalVisible(false);
      fetchProducts();
    }, 1000);
  };

  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          published: '已发布',
          draft: '草稿',
          unpublished: '未发布',
        };
        return statusMap[status] || status;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdated',
      key: 'lastUpdated',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Product) => (
        <div>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditProduct(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteProduct(record.id)}
          >
            删除
          </Button>
          {record.status !== 'published' && (
            <Button
              type="link"
              onClick={() => handlePublishProduct(record.id)}
            >
              发布
            </Button>
          )}
          {record.status === 'published' && (
            <Button
              type="link"
              onClick={() => handleUnpublishProduct(record.id)}
            >
              下架
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="independent-site-product">
      <div className="page-header">
        <h1>独立站商品管理</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAddProduct}
        >
          添加商品
        </Button>
      </div>

      <div className="filter-section">
        <Search
          placeholder="搜索商品名称或SKU"
          style={{ width: 300, marginRight: 16 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="状态"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
        >
          <Option value="">全部</Option>
          <Option value="published">已发布</Option>
          <Option value="draft">草稿</Option>
          <Option value="unpublished">未发布</Option>
        </Select>
      </div>

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

      <Modal
        title={form.getFieldValue('id') ? '编辑商品' : '添加商品'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <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: '请输入价格' }]}
          >
            <Input type="number" placeholder="请输入价格" />
          </Form.Item>

          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <Input type="number" placeholder="请输入库存" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="published">已发布</Option>
              <Option value="draft">草稿</Option>
              <Option value="unpublished">未发布</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="images"
            label="商品图片"
          >
            <Upload
              name="images"
              action="/api/upload"
              listType="picture"
              multiple
            >
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>

          <Form.Item
            name="description"
            label="商品描述"
          >
            <Input.TextArea rows={4} placeholder="请输入商品描述" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
            <Button style={{ marginLeft: 16 }} onClick={() => setModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default IndependentSiteProduct;