import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Spin,
  Row,
  Col,
  Typography,
  Divider,
  Space,
  Tag,
  Popconfirm,
  Alert,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  WarningOutlined,
  UserOutlined,
  EnvironmentOutlined,
  PhoneOutlined,
  MailOutlined,
} from '@ant-design/icons';

const { Option } = Select;
const { Title, Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;

// 模拟黑名单数据
const mockBlacklist = [
  {
    id: 'BL-20260318-001',
    customerName: '张三',
    customerId: 'CUST-001',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    address: '北京市朝阳区',
    reason: '恶意退款',
    level: 'HIGH',
    addedBy: '管理员A',
    addedAt: '2026-03-18T10:00:00Z',
    expireAt: '2026-06-18T00:00:00Z',
  },
  {
    id: 'BL-20260318-002',
    customerName: '李四',
    customerId: 'CUST-002',
    phone: '13900139002',
    email: 'lisi@example.com',
    address: '上海市浦东新区',
    reason: '虚假交易',
    level: 'MEDIUM',
    addedBy: '管理员B',
    addedAt: '2026-03-17T15:30:00Z',
    expireAt: '2026-05-17T00:00:00Z',
  },
  {
    id: 'BL-20260318-003',
    customerName: '王五',
    customerId: 'CUST-003',
    phone: '13700137003',
    email: 'wangwu@example.com',
    address: '广州市天河区',
    reason: '恶意差评',
    level: 'LOW',
    addedBy: '管理员A',
    addedAt: '2026-03-16T14:00:00Z',
    expireAt: '2026-04-16T00:00:00Z',
  },
];

// 黑名单级别选项
const blacklistLevels = [
  { value: 'LOW', label: '低', color: 'blue' },
  { value: 'MEDIUM', label: '中', color: 'orange' },
  { value: 'HIGH', label: '高', color: 'red' },
];

// 黑名单原因选项
const blacklistReasons = [
  { value: 'MALICIOUS_REFUND', label: '恶意退款' },
  { value: 'FAKE_TRANSACTION', label: '虚假交易' },
  { value: 'MALICIOUS_NEGATIVE', label: '恶意差评' },
  { value: 'FRAUD', label: '欺诈行为' },
  { value: 'VIOLATION', label: '违规行为' },
  { value: 'OTHER', label: '其他原因' },
];

const BlacklistManage: React.FC = () => {
  const [form] = Form.useForm();
  const [blacklist, setBlacklist] = useState(mockBlacklist);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [currentItem, setCurrentItem] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [searchText, setSearchText] = useState('');

  // 处理添加黑名单
  const handleAdd = () => {
    setIsEditing(false);
    setCurrentItem(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理编辑黑名单
  const handleEdit = (item: any) => {
    setIsEditing(true);
    setCurrentItem(item);
    form.setFieldsValue({
      customerName: item.customerName,
      customerId: item.customerId,
      phone: item.phone,
      email: item.email,
      address: item.address,
      reason: item.reason,
      level: item.level,
      expireAt: item.expireAt ? new Date(item.expireAt) : null,
    });
    setIsModalVisible(true);
  };

  // 处理删除黑名单
  const handleDelete = (id: string) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      setTimeout(() => {
        const updatedBlacklist = blacklist.filter(item => item.id !== id);
        setBlacklist(updatedBlacklist);
        message.success('删除成功');
        setIsLoading(false);
      }, 500);
    } catch (error) {
      message.error('删除失败');
      setIsLoading(false);
    }
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (isEditing && currentItem) {
        // 编辑模式
        const updatedBlacklist = blacklist.map(item => {
          if (item.id === currentItem.id) {
            return {
              ...item,
              ...values,
              expireAt: values.expireAt ? values.expireAt.toISOString() : null,
            };
          }
          return item;
        });
        setBlacklist(updatedBlacklist);
        message.success('更新成功');
      } else {
        // 添加模式
        const newItem = {
          id: `BL-${Date.now()}`,
          ...values,
          addedBy: '当前用户',
          addedAt: new Date().toISOString(),
          expireAt: values.expireAt ? values.expireAt.toISOString() : null,
        };
        setBlacklist([newItem, ...blacklist]);
        message.success('添加成功');
      }
      setIsModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 获取级别标签
  const getLevelTag = (level: string) => {
    const levelObj = blacklistLevels.find(l => l.value === level);
    return levelObj ? <Tag color={levelObj.color}>{levelObj.label}</Tag> : <Tag>{level}</Tag>;
  };

  // 获取原因标签
  const getReasonTag = (reason: string) => {
    const reasonObj = blacklistReasons.find(r => r.value === reason);
    return reasonObj ? <Tag>{reasonObj.label}</Tag> : <Tag>{reason}</Tag>;
  };

  // 过滤黑名单
  const filteredBlacklist = blacklist.filter(item => 
    item.customerName.includes(searchText) ||
    item.customerId.includes(searchText) ||
    item.phone.includes(searchText) ||
    item.email.includes(searchText)
  );

  // 黑名单表格列
  const columns = [
    {
      title: '黑名单ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '客户信息',
      key: 'customer',
      render: (_, record: any) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{record.customerName}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>ID: {record.customerId}</div>
          <div style={{ fontSize: '12px', color: '#999' }}><PhoneOutlined style={{ marginRight: 4 }} />{record.phone}</div>
          <div style={{ fontSize: '12px', color: '#999' }}><MailOutlined style={{ marginRight: 4 }} />{record.email}</div>
        </div>
      ),
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      render: (address: string) => (
        <div><EnvironmentOutlined style={{ marginRight: 4 }} />{address}</div>
      ),
    },
    {
      title: '原因',
      dataIndex: 'reason',
      key: 'reason',
      render: (reason: string) => getReasonTag(reason),
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => getLevelTag(level),
    },
    {
      title: '添加时间',
      dataIndex: 'addedAt',
      key: 'addedAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '过期时间',
      dataIndex: 'expireAt',
      key: 'expireAt',
      render: (date: string) => date ? new Date(date).toLocaleString() : '永久',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              danger 
              icon={<DeleteOutlined />}
              loading={isLoading}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4} style={{ margin: 0 }}>黑名单管理</Title>
            <Text type="secondary">恶意买家黑名单闭环第一步</Text>
          </div>
        }
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加黑名单
          </Button>
        }
      >
        <Alert
          message="黑名单管理提醒"
          description="黑名单用户将被限制购买和退款权限，请谨慎操作"
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={12}>
            <Input
              placeholder="搜索客户姓名、ID、电话或邮箱"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
          </Col>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Space>
              <Button type="default">导出</Button>
              <Button type="default">导入</Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredBlacklist}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 黑名单编辑模态框 */}
      <Modal
        title={isEditing ? "编辑黑名单" : "添加黑名单"}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="customerName"
                label="客户姓名"
                rules={[{ required: true, message: '请输入客户姓名' }]}
              >
                <Input placeholder="请输入客户姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="customerId"
                label="客户ID"
                rules={[{ required: true, message: '请输入客户ID' }]}
              >
                <Input placeholder="请输入客户ID" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="电话"
                rules={[{ required: true, message: '请输入电话' }]}
              >
                <Input placeholder="请输入电话" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[{ required: true, message: '请输入邮箱' }]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="address"
            label="地址"
            rules={[{ required: true, message: '请输入地址' }]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="reason"
                label="黑名单原因"
                rules={[{ required: true, message: '请选择黑名单原因' }]}
              >
                <Select placeholder="请选择黑名单原因">
                  {blacklistReasons.map(reason => (
                    <Option key={reason.value} value={reason.value}>
                      {reason.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="level"
                label="风险级别"
                rules={[{ required: true, message: '请选择风险级别' }]}
              >
                <Select placeholder="请选择风险级别">
                  {blacklistLevels.map(level => (
                    <Option key={level.value} value={level.value}>
                      {level.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="expireAt"
            label="过期时间"
          >
            <DatePicker
              style={{ width: '100%' }}
              placeholder="选择过期时间（不选则为永久）"
            />
          </Form.Item>

          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea rows={3} placeholder="请输入备注信息" />
          </Form.Item>

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={isLoading}>
                {isEditing ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BlacklistManage;