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

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

const MerchantManage: React.FC = () => {
  const [merchants, setMerchants] = useState<Merchant[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [tierFilter, setTierFilter] = useState<string>('');

  const fetchMerchants = async () => {
    setLoading(true);
    try {
      const response = await getMerchants();
      setMerchants(response.data);
    } catch (error) {
      message.error('获取商户列表失败');
      console.error('获取商户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

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

  const handleTierFilter = (value: string) => {
    setTierFilter(value);
  };

  const filteredMerchants = merchants.filter(merchant => {
    const matchesSearch = merchant.companyName.toLowerCase().includes(searchText.toLowerCase()) ||
                        merchant.contactEmail.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter ? merchant.status === statusFilter : true;
    const matchesTier = tierFilter ? merchant.tier === tierFilter : true;
    return matchesSearch && matchesStatus && matchesTier;
  });

  const handleCreate = () => {
    // 跳转到创建商户页面或打开创建弹窗
    message.info('创建商户功能待实现');
  };

  const handleEdit = (merchant: Merchant) => {
    // 跳转到编辑商户页面或打开编辑弹窗
    message.info(`编辑商户: ${merchant.companyName}`);
  };

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

  const handleView = (merchant: Merchant) => {
    // 跳转到商户详情页面
    message.info(`查看商户详情: ${merchant.companyName}`);
  };

  const columns = [
    {
      title: '商户ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      key: 'companyName',
      ellipsis: true,
    },
    {
      title: '联系邮箱',
      dataIndex: 'contactEmail',
      key: 'contactEmail',
      ellipsis: true,
    },
    {
      title: '联系电话',
      dataIndex: 'contactPhone',
      key: 'contactPhone',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, string> = {
          PENDING: '待审核',
          ACTIVE: '活跃',
          SUSPENDED: '暂停',
          TERMINATED: '终止',
        };
        return <Text>{statusMap[status] || status}</Text>;
      },
    },
    {
      title: '等级',
      dataIndex: 'tier',
      key: 'tier',
      render: (tier: string) => {
        const tierMap: Record<string, string> = {
          BASIC: '基础版',
          PRO: '专业版',
          ENTERPRISE: '企业版',
        };
        return <Text>{tierMap[tier] || tier}</Text>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, merchant: Merchant) => (
        <div>
          <Button 
            icon={<EyeOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleView(merchant)}
          >
            查看
          </Button>
          <Button 
            icon={<EditOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleEdit(merchant)}
          >
            编辑
          </Button>
          <Button 
            icon={<DeleteOutlined />} 
            size="small" 
            danger
            onClick={() => handleDelete(merchant.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 }}>
        <Input
          placeholder="搜索商户名称或邮箱"
          prefix={<SearchOutlined />}
          style={{ width: 300 }}
          onChange={(e) => handleSearch(e.target.value)}
        />
        <Select
          placeholder="筛选状态"
          style={{ width: 120 }}
          onChange={handleStatusFilter}
          allowClear
        >
          <Option value="PENDING">待审核</Option>
          <Option value="ACTIVE">活跃</Option>
          <Option value="SUSPENDED">暂停</Option>
          <Option value="TERMINATED">终止</Option>
        </Select>
        <Select
          placeholder="筛选等级"
          style={{ width: 120 }}
          onChange={handleTierFilter}
          allowClear
        >
          <Option value="BASIC">基础版</Option>
          <Option value="PRO">专业版</Option>
          <Option value="ENTERPRISE">企业版</Option>
        </Select>
      </div>

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

export default MerchantManage;