import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Select, message, Card, Typography, Form, Modal } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { merchantDataSource, MerchantShop, Merchant } from '@/services/merchantDataSource';

const { Option } = Select;
const { Title, Text } = Typography;
const { Item } = Form;

const MerchantShopManage: React.FC = () => {
  const [shops, setShops] = useState<Shop[]>([]);
  const [merchants, setMerchants] = useState<{ id: string; companyName: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [merchantFilter, setMerchantFilter] = useState<string>('');
  const [platformFilter, setPlatformFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingShop, setEditingShop] = useState<Shop | null>(null);

  const fetchShops = async () => {
    setLoading(true);
    try {
      const response = await getMerchantShops();
      setShops(response.data);
    } catch (error) {
      message.error('获取店铺列表失败');
      console.error('获取店铺列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchMerchants = async () => {
    try {
      // 实际项目中应该调用获取商户列表的API
      // 这里模拟数据
      setMerchants([
        { id: '1', companyName: '商户A' },
        { id: '2', companyName: '商户B' },
        { id: '3', companyName: '商户C' },
      ]);
    } catch (error) {
      console.error('获取商户列表失败:', error);
    }
  };

  useEffect(() => {
    fetchMerchants();
    fetchShops();
  }, []);

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

  const handleMerchantFilter = (value: string) => {
    setMerchantFilter(value);
  };

  const handlePlatformFilter = (value: string) => {
    setPlatformFilter(value);
  };

  const handleStatusFilter = (value: string) => {
    setStatusFilter(value);
  };

  const filteredShops = shops.filter(shop => {
    const matchesSearch = shop.shopName.toLowerCase().includes(searchText.toLowerCase()) ||
                        shop.shopUrl.toLowerCase().includes(searchText.toLowerCase());
    const matchesMerchant = merchantFilter ? shop.merchantId === merchantFilter : true;
    const matchesPlatform = platformFilter ? shop.platform === platformFilter : true;
    const matchesStatus = statusFilter ? shop.status === statusFilter : true;
    return matchesSearch && matchesMerchant && matchesPlatform && matchesStatus;
  });

  const handleCreate = () => {
    setEditingShop(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (shop: Shop) => {
    setEditingShop(shop);
    form.setFieldsValue(shop);
    setIsModalVisible(true);
  };

  const handleDelete = (shopId: string) => {
    // 确认删除后调用API
    message.info(`删除店铺: ${shopId}`);
  };

  const handleView = (shop: Shop) => {
    // 跳转到店铺详情页面
    message.info(`查看店铺详情: ${shop.shopName}`);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingShop) {
        // 编辑店铺
        await updateMerchantShop(editingShop.id, values);
        message.success('店铺更新成功');
      } else {
        // 创建店铺
        await createMerchantShop(values);
        message.success('店铺创建成功');
      }
      setIsModalVisible(false);
      fetchShops();
    } catch (error) {
      message.error('操作失败');
      console.error('操作失败:', error);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const columns = [
    {
      title: '店铺ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '商户',
      dataIndex: 'merchantId',
      key: 'merchantId',
      render: (merchantId: string) => {
        const merchant = merchants.find(m => m.id === merchantId);
        return <Text>{merchant?.companyName || merchantId}</Text>;
      },
    },
    {
      title: '店铺名称',
      dataIndex: 'shopName',
      key: 'shopName',
      ellipsis: true,
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      ellipsis: true,
    },
    {
      title: '店铺链接',
      dataIndex: 'shopUrl',
      key: 'shopUrl',
      ellipsis: true,
      render: (shopUrl: string) => (
        <a href={shopUrl} target="_blank" rel="noopener noreferrer">
          {shopUrl}
        </a>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, string> = {
          ACTIVE: '活跃',
          INACTIVE: '未激活',
          SUSPENDED: '暂停',
        };
        return <Text>{statusMap[status] || status}</Text>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, shop: Shop) => (
        <div>
          <Button 
            icon={<EyeOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleView(shop)}
          >
            查看
          </Button>
          <Button 
            icon={<EditOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleEdit(shop)}
          >
            编辑
          </Button>
          <Button 
            icon={<DeleteOutlined />} 
            size="small" 
            danger
            onClick={() => handleDelete(shop.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>商户店铺管理</Title>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleCreate}
        >
          新增店铺
        </Button>
      </div>

      <div style={{ display: 'flex', marginBottom: 16, gap: 16, flexWrap: 'wrap' }}>
        <Input
          placeholder="搜索店铺名称或链接"
          prefix={<SearchOutlined />}
          style={{ width: 300 }}
          onChange={(e) => handleSearch(e.target.value)}
        />
        <Select
          placeholder="筛选商户"
          style={{ width: 200 }}
          onChange={handleMerchantFilter}
          allowClear
        >
          {merchants.map(merchant => (
            <Option key={merchant.id} value={merchant.id}>
              {merchant.companyName}
            </Option>
          ))}
        </Select>
        <Select
          placeholder="筛选平台"
          style={{ width: 120 }}
          onChange={handlePlatformFilter}
          allowClear
        >
          <Option value="Amazon">Amazon</Option>
          <Option value="eBay">eBay</Option>
          <Option value="Shopee">Shopee</Option>
          <Option value="TikTok">TikTok</Option>
        </Select>
        <Select
          placeholder="筛选状态"
          style={{ width: 120 }}
          onChange={handleStatusFilter}
          allowClear
        >
          <Option value="ACTIVE">活跃</Option>
          <Option value="INACTIVE">未激活</Option>
          <Option value="SUSPENDED">暂停</Option>
        </Select>
      </div>

      <Table
        columns={columns}
        dataSource={filteredShops}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          defaultPageSize: 10,
        }}
      />

      <Modal
        title={editingShop ? '编辑店铺' : '新增店铺'}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Item
            name="merchantId"
            label="商户"
            rules={[{ required: true, message: '请选择商户' }]}
          >
            <Select placeholder="选择商户">
              {merchants.map(merchant => (
                <Option key={merchant.id} value={merchant.id}>
                  {merchant.companyName}
                </Option>
              ))}
            </Select>
          </Item>
          <Item
            name="shopName"
            label="店铺名称"
            rules={[{ required: true, message: '请输入店铺名称' }]}
          >
            <Input placeholder="请输入店铺名称" />
          </Item>
          <Item
            name="platform"
            label="平台"
            rules={[{ required: true, message: '请选择平台' }]}
          >
            <Select placeholder="选择平台">
              <Option value="Amazon">Amazon</Option>
              <Option value="eBay">eBay</Option>
              <Option value="Shopee">Shopee</Option>
              <Option value="TikTok">TikTok</Option>
            </Select>
          </Item>
          <Item
            name="shopUrl"
            label="店铺链接"
            rules={[{ required: true, message: '请输入店铺链接' }]}
          >
            <Input placeholder="请输入店铺链接" />
          </Item>
          <Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="选择状态">
              <Option value="ACTIVE">活跃</Option>
              <Option value="INACTIVE">未激活</Option>
              <Option value="SUSPENDED">暂停</Option>
            </Select>
          </Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default MerchantShopManage;