import {
  useState,
  useEffect,
  useParams,
  Table,
  Button,
  Input,
  Select,
  message,
  Upload,
  Modal,
  Form,
  Card,
  Row,
  Col,
  Tag,
  Space,
  Typography,
  Statistic,
  Image,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  ExportOutlined,
  ReloadOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  InboxOutlined,
  Option,
  Search,
  Title,
  Text,
  Key,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import { independentSiteDataSource, SiteProduct } from '@/services/independentSiteDataSource';

const IndependentSiteProduct: FC = () => {
  const { id } = useParams<{ id: string }>();
  const [products, setProducts] = useState<SiteProduct[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [filters, setFilters] = useState({ status: '', search: '', category: '' });
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<SiteProduct | null>(null);
  const [form] = Form.useForm();

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

  const fetchProducts = async () => {
    setLoading(true);
    try {
      // 这里应该调用 independentSiteDataSource 的商品列表方法
      // 由于当前数据源没有专门的商品方法，暂时使用模拟数据
      const mockProducts: SiteProduct[] = [
        { id: '1', siteId: id || '', name: '无线蓝牙耳机 Pro', sku: 'WBH-001', price: 99.99, stock: 150, status: 'published', category: '电子产品', createdAt: '2026-03-01', updatedAt: '2026-03-15' },
        { id: '2', siteId: id || '', name: '智能手表 S3', sku: 'SW-002', price: 199.99, stock: 80, status: 'published', category: '电子产品', createdAt: '2026-03-05', updatedAt: '2026-03-10' },
        { id: '3', siteId: id || '', name: '便携充电宝 20000mAh', sku: 'PB-003', price: 49.99, stock: 200, status: 'published', category: '配件', createdAt: '2026-03-10', updatedAt: '2026-03-18' },
        { id: '4', siteId: id || '', name: '手机支架 磁吸款', sku: 'MS-004', price: 29.99, stock: 300, status: 'draft', category: '配件', createdAt: '2026-03-12', updatedAt: '2026-03-12' },
        { id: '5', siteId: id || '', name: '数据线套装 Type-C', sku: 'DC-005', price: 19.99, stock: 500, status: 'unpublished', category: '配件', createdAt: '2026-03-15', updatedAt: '2026-03-15' },
      ];
      let filtered = [...mockProducts];
      if (filters.status) {
        filtered = filtered.filter(p => p.status === filters.status);
      }
      if (filters.category) {
        filtered = filtered.filter(p => p.category === filters.category);
      }
      if (filters.search) {
        filtered = filtered.filter(p => 
          p.name.toLowerCase().includes(filters.search.toLowerCase()) ||
          p.sku.toLowerCase().includes(filters.search.toLowerCase())
        );
      }
      setProducts(filtered);
    } catch (error) {
      console.error('Failed to load products:', error);
      message.error('加载商品失败');
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleDeleteProduct = (productId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个商品吗？',
      onOk: async () => {
        try {
          // 这里应该调用 independentSiteDataSource 的删除商品方法
          setProducts(prev => prev.filter(p => p.id !== productId));
          message.success('商品已删除');
        } catch (error) {
          console.error('Failed to delete product:', error);
          message.error('删除商品失败');
        }
      },
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的商品');
      return;
    }
    Modal.confirm({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个商品吗？`,
      onOk: async () => {
        try {
          // 这里应该调用 independentSiteDataSource 的批量删除商品方法
          setProducts(prev => prev.filter(p => !selectedRowKeys.includes(p.id)));
          setSelectedRowKeys([]);
          message.success('商品已批量删除');
        } catch (error) {
          console.error('Failed to batch delete products:', error);
          message.error('批量删除商品失败');
        }
      },
    });
  };

  const handlePublishProduct = async (productId: string) => {
    try {
      // 这里应该调用 independentSiteDataSource 的更新商品方法
      setProducts(prev => prev.map(p => p.id === productId ? { ...p, status: 'published' } : p));
      message.success('商品已发布');
    } catch (error) {
      console.error('Failed to publish product:', error);
      message.error('发布商品失败');
    }
  };

  const handleBatchPublish = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要发布的商品');
      return;
    }
    try {
      // 这里应该调用 independentSiteDataSource 的批量更新商品方法
      setProducts(prev => prev.map(p => selectedRowKeys.includes(p.id) ? { ...p, status: 'published' } : p));
      setSelectedRowKeys([]);
      message.success('商品已批量发布');
    } catch (error) {
      console.error('Failed to batch publish products:', error);
      message.error('批量发布商品失败');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      if (editingProduct) {
        // 这里应该调用 independentSiteDataSource 的更新商品方法
        setProducts(prev => prev.map(p => p.id === editingProduct.id ? { ...p, ...values } : p));
        message.success('商品更新成功');
      } else {
        // 这里应该调用 independentSiteDataSource 的创建商品方法
        const newProduct: SiteProduct = {
          ...values,
          id: `${Date.now()}`,
          siteId: id || '',
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0],
        };
        setProducts(prev => [...prev, newProduct]);
        message.success('商品添加成功');
      }
    } catch (error) {
      console.error('Failed to save product:', error);
      message.error('保存商品失败');
    } finally {
      setLoading(false);
      setModalVisible(false);
    }
  };

  const statusColors: Record<string, string> = {
    published: 'success',
    draft: 'warning',
    unpublished: 'default',
  };

  const statusTexts: Record<string, string> = {
    published: '已发布',
    draft: '草稿',
    unpublished: '未发布',
  };

  const columns: ColumnsType<SiteProduct> = [
    {
      title: '商品信息',
      dataIndex: 'name',
      key: 'name',
      width: 280,
      render: (text, record) => (
        <Space>
          <Image src={record.image} width={60} height={60} style={{ borderRadius: 4, objectFit: 'cover' }} fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" />
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <Text type="secondary" style={{ fontSize: 12 }}>SKU: {record.sku}</Text>
            <div><Tag>{record.category}</Tag></div>
          </div>
        </Space>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 120,
      render: (price, record) => (
        <div>
          <div style={{ fontWeight: 500, color: '#ff4d4f' }}>${price.toFixed(2)}</div>
          {record.comparePrice && <Text delete type="secondary" style={{ fontSize: 12 }}>${record.comparePrice.toFixed(2)}</Text>}
        </div>
      ),
    },
    {
      title: '成本',
      dataIndex: 'cost',
      key: 'cost',
      width: 80,
      render: (cost) => cost ? `$${cost.toFixed(2)}` : '-',
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 80,
      render: (stock) => (
        <Tag color={stock > 50 ? 'success' : stock > 10 ? 'warning' : 'error'}>{stock}</Tag>
      ),
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
      width: 80,
      sorter: (a, b) => a.sales - b.sales,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => <Tag color={statusColors[status]}>{statusTexts[status]}</Tag>,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEditProduct(record)}>编辑</Button>
          {record.status !== 'published' && (
            <Button type="link" size="small" onClick={() => handlePublishProduct(record.id)}>发布</Button>
          )}
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDeleteProduct(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

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

  const totalStock = products.reduce((sum, p) => sum + p.stock, 0);
  const totalSales = products.reduce((sum, p) => sum + p.sales, 0);
  const totalValue = products.reduce((sum, p) => sum + (p.price * p.stock), 0);
  const publishedCount = products.filter(p => p.status === 'published').length;

  return (
    <div className="independent-site-product" style={{ padding: 24 }}>
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Title level={4}>商品管理</Title>
          <Text type="secondary">站点ID: {id}</Text>
        </Col>
        <Col>
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchProducts}>刷新</Button>
            <Button icon={<ExportOutlined />}>导出</Button>
            <Upload showUploadList={false}>
              <Button icon={<UploadOutlined />}>批量导入</Button>
            </Upload>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddProduct}>添加商品</Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="商品总数" value={products.length} prefix={<ShoppingCartOutlined />} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="已发布" value={publishedCount} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="总库存" value={totalStock} prefix={<InboxOutlined />} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="库存价值" value={totalValue} precision={2} prefix={<DollarOutlined />} />
          </Card>
        </Col>
      </Row>

      <Card>
        <Row justify="space-between" style={{ marginBottom: 16 }}>
          <Col>
            <Space>
              <Search
                placeholder="搜索商品名称或SKU"
                style={{ width: 250 }}
                onSearch={(value) => setFilters({ ...filters, search: value })}
                allowClear
              />
              <Select
                placeholder="商品状态"
                style={{ width: 120 }}
                onChange={(value) => setFilters({ ...filters, status: value })}
                allowClear
              >
                <Option value="published">已发布</Option>
                <Option value="draft">草稿</Option>
                <Option value="unpublished">未发布</Option>
              </Select>
              <Select
                placeholder="商品分类"
                style={{ width: 120 }}
                onChange={(value) => setFilters({ ...filters, category: value })}
                allowClear
              >
                <Option value="电子产品">电子产品</Option>
                <Option value="配件">配件</Option>
              </Select>
            </Space>
          </Col>
          <Col>
            <Space>
              {selectedRowKeys.length > 0 && (
                <>
                  <Button onClick={handleBatchPublish}>批量发布 ({selectedRowKeys.length})</Button>
                  <Button danger onClick={handleBatchDelete}>批量删除 ({selectedRowKeys.length})</Button>
                </>
              )}
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={products}
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          pagination={{ pageSize: 10, showSizeChanger: true, showQuickJumper: true }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal
        title={editingProduct ? '编辑商品' : '添加商品'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
        confirmLoading={loading}
      >
        <Form form={form} onFinish={handleSubmit} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="商品名称" rules={[{ required: true, message: '请输入商品名称' }]}>
                <Input placeholder="请输入商品名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="sku" label="SKU" rules={[{ required: true, message: '请输入SKU' }]}>
                <Input placeholder="请输入SKU" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="price" label="售价" rules={[{ required: true, message: '请输入售价' }]}>
                <Input type="number" prefix="$" placeholder="0.00" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="comparePrice" label="原价">
                <Input type="number" prefix="$" placeholder="0.00" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="cost" label="成本">
                <Input type="number" prefix="$" placeholder="0.00" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="stock" label="库存" rules={[{ required: true, message: '请输入库存' }]}>
                <Input type="number" placeholder="0" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="category" label="分类" rules={[{ required: true, message: '请选择分类' }]}>
                <Select placeholder="请选择分类">
                  <Option value="电子产品">电子产品</Option>
                  <Option value="配件">配件</Option>
                  <Option value="服装">服装</Option>
                  <Option value="家居">家居</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="status" label="状态" initialValue="draft">
            <Select>
              <Option value="published">已发布</Option>
              <Option value="draft">草稿</Option>
              <Option value="unpublished">未发布</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default IndependentSiteProduct;
