import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Spin,
  Row,
  Col,
  Typography,
  Divider,
  Space,
  Tag,
  Alert,
  Statistic,
  Progress,
  Badge,
} from 'antd';
import {
  WarningOutlined,
  SearchOutlined,
  EyeOutlined,
  AlertOutlined,
  LineChartOutlined,
  ShieldOutlined,
} from '@ant-design/icons';

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

// 模拟风险数据
const mockRisks = [
  {
    id: 'RISK-20260318-001',
    customerId: 'CUST-001',
    customerName: '张三',
    riskType: 'MALICIOUS_REFUND',
    riskLevel: 'HIGH',
    score: 95,
    description: '短时间内多次申请退款',
    status: 'PENDING',
    detectedAt: '2026-03-18T10:00:00Z',
    lastUpdated: '2026-03-18T10:00:00Z',
  },
  {
    id: 'RISK-20260318-002',
    customerId: 'CUST-002',
    customerName: '李四',
    riskType: 'FAKE_TRANSACTION',
    riskLevel: 'MEDIUM',
    score: 75,
    description: '同一IP地址多次下单',
    status: 'PROCESSING',
    detectedAt: '2026-03-17T15:30:00Z',
    lastUpdated: '2026-03-18T09:00:00Z',
  },
  {
    id: 'RISK-20260318-003',
    customerId: 'CUST-003',
    customerName: '王五',
    riskType: 'MALICIOUS_NEGATIVE',
    riskLevel: 'LOW',
    score: 45,
    description: '多次给出恶意差评',
    status: 'RESOLVED',
    detectedAt: '2026-03-16T14:00:00Z',
    lastUpdated: '2026-03-17T10:00:00Z',
  },
];

// 风险类型选项
const riskTypes = [
  { value: 'MALICIOUS_REFUND', label: '恶意退款' },
  { value: 'FAKE_TRANSACTION', label: '虚假交易' },
  { value: 'MALICIOUS_NEGATIVE', label: '恶意差评' },
  { value: 'FRAUD', label: '欺诈行为' },
  { value: 'VIOLATION', label: '违规行为' },
  { value: 'OTHER', label: '其他风险' },
];

// 风险级别选项
const riskLevels = [
  { value: 'LOW', label: '低', color: 'blue' },
  { value: 'MEDIUM', label: '中', color: 'orange' },
  { value: 'HIGH', label: '高', color: 'red' },
];

// 风险状态选项
const riskStatuses = [
  { value: 'PENDING', label: '待处理' },
  { value: 'PROCESSING', label: '处理中' },
  { value: 'RESOLVED', label: '已解决' },
  { value: 'IGNORED', label: '已忽略' },
];

const RiskMonitor: React.FC = () => {
  const [form] = Form.useForm();
  const [risks, setRisks] = useState(mockRisks);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentRisk, setCurrentRisk] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [riskStats, setRiskStats] = useState({
    total: 100,
    high: 30,
    medium: 40,
    low: 30,
  });

  // 处理风险详情查看
  const handleRiskView = (risk: any) => {
    setCurrentRisk(risk);
    setIsModalVisible(true);
  };

  // 处理风险状态更新
  const handleStatusUpdate = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const updatedRisks = risks.map(risk => {
        if (risk.id === currentRisk.id) {
          return {
            ...risk,
            status: values.status,
            lastUpdated: new Date().toISOString(),
          };
        }
        return risk;
      });
      
      setRisks(updatedRisks);
      setCurrentRisk(updatedRisks.find(r => r.id === currentRisk.id));
      message.success('状态更新成功');
    } catch (error) {
      message.error('状态更新失败');
    } finally {
      setIsLoading(false);
    }
  };

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

  // 获取风险类型标签
  const getTypeTag = (type: string) => {
    const typeObj = riskTypes.find(t => t.value === type);
    return typeObj ? <Tag>{typeObj.label}</Tag> : <Tag>{type}</Tag>;
  };

  // 获取风险状态标签
  const getStatusTag = (status: string) => {
    const statusObj = riskStatuses.find(s => s.value === status);
    switch (status) {
      case 'PENDING':
        return <Tag color="blue">{statusObj?.label}</Tag>;
      case 'PROCESSING':
        return <Tag color="processing">{statusObj?.label}</Tag>;
      case 'RESOLVED':
        return <Tag color="success">{statusObj?.label}</Tag>;
      case 'IGNORED':
        return <Tag color="default">{statusObj?.label}</Tag>;
      default:
        return <Tag>{statusObj?.label || status}</Tag>;
    }
  };

  // 过滤风险
  const filteredRisks = risks.filter(risk => 
    risk.customerName.includes(searchText) ||
    risk.customerId.includes(searchText) ||
    risk.id.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>
      ),
    },
    {
      title: '风险类型',
      dataIndex: 'riskType',
      key: 'riskType',
      render: (type: string) => getTypeTag(type),
    },
    {
      title: '风险级别',
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      render: (level: string) => getLevelTag(level),
    },
    {
      title: '风险评分',
      dataIndex: 'score',
      key: 'score',
      render: (score: number) => (
        <div>
          <Progress 
            percent={score} 
            status={score > 70 ? 'exception' : score > 40 ? 'normal' : 'success'}
            size="small"
          />
          <Text style={{ display: 'block', textAlign: 'center', marginTop: 4 }}>
            {score}
          </Text>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '检测时间',
      dataIndex: 'detectedAt',
      key: 'detectedAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button 
          type="primary" 
          icon={<EyeOutlined />} 
          onClick={() => handleRiskView(record)}
        >
          查看
        </Button>
      ),
    },
  ];

  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" ghost>
            风险设置
          </Button>
        }
      >
        <Alert
          message="风险监控提醒"
          description="系统会自动检测潜在风险，高风险用户将被自动加入黑名单"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic 
                title="总风险数" 
                value={riskStats.total} 
                prefix={<AlertOutlined />} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="高风险" 
                value={riskStats.high} 
                prefix={<WarningOutlined />} 
                valueStyle={{ color: '#ff4d4f' }} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="中风险" 
                value={riskStats.medium} 
                prefix={<AlertOutlined />} 
                valueStyle={{ color: '#faad14' }} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="低风险" 
                value={riskStats.low} 
                prefix={<ShieldOutlined />} 
                valueStyle={{ color: '#52c41a' }} 
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={12}>
            <Input
              placeholder="搜索客户姓名、ID或风险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={filteredRisks}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 风险详情模态框 */}
      {currentRisk && (
        <Modal
          title="风险详情"
          open={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={null}
          width={800}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Statistic
                title="风险评分"
                value={currentRisk.score}
                valueStyle={{ color: currentRisk.score > 70 ? '#ff4d4f' : currentRisk.score > 40 ? '#faad14' : '#52c41a' }}
                prefix={<WarningOutlined />}
              />
              <div style={{ marginTop: 16 }}>
                <Title level={5}>风险信息</Title>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>风险ID:</Text> {currentRisk.id}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>客户姓名:</Text> {currentRisk.customerName}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>客户ID:</Text> {currentRisk.customerId}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>风险类型:</Text> {getTypeTag(currentRisk.riskType)}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>风险级别:</Text> {getLevelTag(currentRisk.riskLevel)}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>状态:</Text> {getStatusTag(currentRisk.status)}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>检测时间:</Text> {new Date(currentRisk.detectedAt).toLocaleString()}
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>最后更新:</Text> {new Date(currentRisk.lastUpdated).toLocaleString()}
                </div>
              </div>
            </Col>
            <Col span={12}>
              <div style={{ marginBottom: 16 }}>
                <Title level={5}>风险描述</Title>
                <div style={{ padding: 16, backgroundColor: '#f0f0f0', borderRadius: 4 }}>
                  {currentRisk.description}
                </div>
              </div>
              <div>
                <Title level={5}>处理建议</Title>
                <div style={{ padding: 16, backgroundColor: '#f6ffed', borderRadius: 4, border: '1px solid #b7eb8f' }}>
                  {currentRisk.riskLevel === 'HIGH' && (
                    <>
                      <p>1. 立即将该用户加入黑名单</p>
                      <p>2. 暂停处理该用户的所有订单</p>
                      <p>3. 联系用户核实情况</p>
                    </>
                  )}
                  {currentRisk.riskLevel === 'MEDIUM' && (
                    <>
                      <p>1. 密切监控该用户的行为</p>
                      <p>2. 审核该用户的订单</p>
                      <p>3. 考虑限制部分功能</p>
                    </>
                  )}
                  {currentRisk.riskLevel === 'LOW' && (
                    <>
                      <p>1. 轻微关注该用户的行为</p>
                      <p>2. 正常处理订单</p>
                      <p>3. 记录风险信息</p>
                    </>
                  )}
                </div>
              </div>
            </Col>
          </Row>

          <Divider orientation="left">状态更新</Divider>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleStatusUpdate}
            initialValues={{ status: currentRisk.status }}
          >
            <Form.Item
              name="status"
              label="处理状态"
              rules={[{ required: true, message: '请选择处理状态' }]}
            >
              <Select placeholder="请选择处理状态">
                {riskStatuses.map(status => (
                  <Option key={status.value} value={status.value}>
                    {status.label}
                  </Option>
                ))}
              </Select>
            </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}>
                  更新状态
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      )}
    </div>
  );
};

export default RiskMonitor;