import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  InputNumber,
  Descriptions,
  Divider,
  message,
  Tag,
  Tabs,
  Row,
  Col,
  Statistic,
  Alert,
  Tooltip,
  Badge,
  Upload,
  Radio,
  Slider,
  Switch,
  Popconfirm,
  UserOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  StopOutlined,
  ExclamationCircleOutlined,
  UploadOutlined,
  DownloadOutlined,
  BulbOutlined,
  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  RestOutlined,
  FilterOutlined,
  FileExcelOutlined,
  FileTextOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  WarningOutlined,
  Option,
  TextArea,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { blacklistDataSource, BlacklistRecord, BlacklistRule } from '@/services/blacklistDataSource';

interface BlacklistFormData {
  shop_id: string;
  buyer_id: string;
  buyer_name: string;
  buyer_email: string;
  buyer_phone?: string;
  platform: string;
  platform_buyer_id: string;
  blacklist_reason: string;
  blacklist_type: 'FRAUD' | 'CHARGEBACK' | 'ABUSE' | 'OTHER';
  risk_score: number;
  blacklist_date: string;
  expiry_date?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'EXPIRED';
  evidence?: string;
  created_by: string;
  trace_id: string;
  created_at: string;
  updated_at: string;
}

interface BlacklistRuleFormData {
  name: string;
  description: string;
  condition_type: 'TRANSACTION' | 'BEHAVIOR' | 'COMPLIANCE';
  threshold: number;
  risk_score: number;
  blacklist_type: 'FRAUD' | 'CHARGEBACK' | 'ABUSE' | 'OTHER';
  auto_blacklist: boolean;
  enabled: boolean;
  expiry_days: number;
  platforms: string[];
}

const RULE_CONDITIONS = [
  { value: 'TRANSACTION', label: 'Transaction', description: '基于交易行为' },
  { value: 'BEHAVIOR', label: 'Behavior', description: '基于用户行为' },
  { value: 'COMPLIANCE', label: 'Compliance', description: '基于合规要求' },
];

const MOCK_RULES: BlacklistRule[] = [
  {
    id: '1',
    name: 'High Chargeback Rate',
    description: 'Chargeback rate > 5%',
    condition: 'chargeback_rate > 5',
    condition_type: 'TRANSACTION',
    threshold: 5,
    action: 'BLOCK',
    status: 'ACTIVE',
    risk_score: 80,
    blacklist_type: 'CHARGEBACK',
    auto_blacklist: true,
    enabled: true,
    expiry_days: 365,
    platforms: ['Amazon', 'eBay', 'Shopify'],
    createdBy: 'admin',
    createdAt: '2026-01-01 10:00:00',
    updatedAt: '2026-01-01 10:00:00',
    created_by: 'admin',
    created_at: '2026-01-01 10:00:00',
    updated_at: '2026-01-01 10:00:00',
  },
  {
    id: '2',
    name: 'Multiple Returns',
    description: 'Returns > 3 in 30 days',
    condition: 'returns_count > 3',
    condition_type: 'BEHAVIOR',
    threshold: 3,
    action: 'ALERT',
    status: 'ACTIVE',
    risk_score: 65,
    blacklist_type: 'ABUSE',
    auto_blacklist: true,
    enabled: true,
    expiry_days: 180,
    platforms: ['Amazon', 'eBay'],
    createdBy: 'admin',
    createdAt: '2026-01-05 14:30:00',
    updatedAt: '2026-01-05 14:30:00',
    created_by: 'admin',
    created_at: '2026-01-05 14:30:00',
    updated_at: '2026-01-05 14:30:00',
  },
  {
    id: '3',
    name: 'Suspicious IP Address',
    description: 'Known suspicious IP ranges',
    condition: 'ip_in_suspicious_ranges',
    condition_type: 'COMPLIANCE',
    threshold: 1,
    action: 'BLOCK',
    status: 'ACTIVE',
    risk_score: 90,
    blacklist_type: 'FRAUD',
    auto_blacklist: true,
    enabled: true,
    expiry_days: 365,
    platforms: ['All'],
    createdBy: 'admin',
    createdAt: '2026-01-10 09:15:00',
    updatedAt: '2026-01-10 09:15:00',
    created_by: 'admin',
    created_at: '2026-01-10 09:15:00',
    updated_at: '2026-01-10 09:15:00',
  },
];

const BLACKLIST_TYPES = [
  { value: 'FRAUD', label: 'Fraud', color: 'red' },
  { value: 'CHARGEBACK', label: 'Chargeback', color: 'orange' },
  { value: 'ABUSE', label: 'Abuse', color: 'purple' },
  { value: 'OTHER', label: 'Other', color: 'default' },
];

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  ACTIVE: { color: 'error', text: 'Active', icon: <StopOutlined /> },
  INACTIVE: { color: 'default', text: 'Inactive', icon: <CloseCircleOutlined /> },
  EXPIRED: { color: 'default', text: 'Expired', icon: <ExclamationCircleOutlined /> },
};

const RULE_STATUS = [
  { value: 'enabled', label: 'Enabled', color: 'green' },
  { value: 'disabled', label: 'Disabled', color: 'default' },
];

const PLATFORMS = [
  'Amazon',
  'eBay',
  'Shopify',
  'Walmart',
  'TikTok Shop',
  'Temu',
  'Alibaba',
  'Other',
];

const MOCK_BLACKLISTS: BlacklistRecord[] = [
  {
    id: '1',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    business_type: 'TOC',
    buyer_id: 'buyer-001',
    buyer_name: 'John Smith',
    buyer_email: 'john.smith@example.com',
    buyer_phone: '+1-555-0101',
    platform: 'Amazon',
    platform_buyer_id: 'AMZ-001',
    blacklist_reason: 'Multiple fraudulent transactions',
    blacklist_type: 'FRAUD',
    risk_score: 85,
    blacklist_date: '2026-01-15',
    expiry_date: '2027-01-15',
    status: 'ACTIVE',
    evidence: 'Transaction records, IP logs',
    created_by: 'admin',
    trace_id: 'trace-001',
    created_at: '2026-01-15 10:00:00',
    updated_at: '2026-01-15 10:00:00',
  },
  {
    id: '2',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    business_type: 'TOC',
    buyer_id: 'buyer-002',
    buyer_name: 'Jane Doe',
    buyer_email: 'jane.doe@example.com',
    platform: 'eBay',
    platform_buyer_id: 'EBAY-002',
    blacklist_reason: 'Excessive chargebacks',
    blacklist_type: 'CHARGEBACK',
    risk_score: 75,
    blacklist_date: '2026-02-20',
    expiry_date: '2026-08-20',
    status: 'ACTIVE',
    evidence: 'Chargeback documentation',
    created_by: 'admin',
    trace_id: 'trace-002',
    created_at: '2026-02-20 14:30:00',
    updated_at: '2026-02-20 14:30:00',
  },
  {
    id: '3',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    business_type: 'TOC',
    buyer_id: 'buyer-003',
    buyer_name: 'Mike Johnson',
    buyer_email: 'mike.j@example.com',
    platform: 'Amazon',
    platform_buyer_id: 'AMZ-003',
    blacklist_reason: 'Abusive behavior towards support',
    blacklist_type: 'ABUSE',
    risk_score: 60,
    blacklist_date: '2026-03-01',
    expiry_date: '2026-06-01',
    status: 'ACTIVE',
    evidence: 'Support chat logs',
    created_by: 'admin',
    trace_id: 'trace-003',
    created_at: '2026-03-01 09:15:00',
    updated_at: '2026-03-01 09:15:00',
  },
  {
    id: '4',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    business_type: 'TOC',
    buyer_id: 'buyer-004',
    buyer_name: 'Sarah Wilson',
    buyer_email: 'sarah.w@example.com',
    platform: 'Shopify',
    platform_buyer_id: 'SHOPIFY-004',
    blacklist_reason: 'Suspicious ordering pattern',
    blacklist_type: 'OTHER',
    risk_score: 50,
    blacklist_date: '2026-02-10',
    expiry_date: '2026-05-10',
    status: 'INACTIVE',
    evidence: 'Order history analysis',
    created_by: 'admin',
    trace_id: 'trace-004',
    created_at: '2026-02-10 11:00:00',
    updated_at: '2026-03-01 16:00:00',
  },
];

const BlacklistManage: FC = () => {
  const [form] = Form.useForm();
  const [ruleForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [blacklists, setBlacklists] = useState<BlacklistRecord[]>(MOCK_BLACKLISTS);
  const [rules, setRules] = useState<BlacklistRule[]>(MOCK_RULES);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [ruleModalVisible, setRuleModalVisible] = useState(false);
  const [selectedBlacklist, setSelectedBlacklist] = useState<BlacklistRecord | null>(null);
  const [selectedRule, setSelectedRule] = useState<BlacklistRule | null>(null);
  const [activeTab, setActiveTab] = useState('all');
  const [activeRuleTab, setActiveRuleTab] = useState('rules');
  const [searchText, setSearchText] = useState('');
  const [platformFilter, setPlatformFilter] = useState<string>('');
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRuleKeys, setSelectedRuleKeys] = useState<React.Key[]>([]);
  const [rulesLoading, setRulesLoading] = useState(false);

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

  const fetchBlacklists = async () => {
    setLoading(true);
    try {
      setBlacklists(MOCK_BLACKLISTS);
    } finally {
      setLoading(false);
    }
  };

  const fetchRules = async () => {
    setLoading(true);
    try {
      setRules(MOCK_RULES);
    } finally {
      setLoading(false);
    }
  };

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

  const handleAddRule = () => {
    setSelectedRule(null);
    ruleForm.resetFields();
    setRuleModalVisible(true);
  };

  const handleEditRule = (rule: BlacklistRule) => {
    setSelectedRule(rule);
    ruleForm.setFieldsValue(rule);
    setRuleModalVisible(true);
  };

  const handleDeleteRule = (id: string) => {
    Modal.confirm({
      title: 'Delete Rule',
      content: 'Are you sure you want to delete this rule?',
      okType: 'danger',
      onOk: () => {
        setRules(rules.filter(rule => rule.id !== id));
        message.success('Rule deleted successfully');
      },
    });
  };

  const handleToggleRule = (id: string) => {
    setRules(rules.map(rule => 
      rule.id === id ? { ...rule, enabled: !rule.enabled, updated_at: new Date().toISOString() } : rule
    ));
    message.success('Rule status updated');
  };

  const handleBatchDeleteRules = () => {
    if (selectedRuleKeys.length === 0) {
      message.warning('Please select rules to delete');
      return;
    }

    Modal.confirm({
      title: 'Batch Delete Rules',
      content: `Are you sure you want to delete ${selectedRuleKeys.length} rules?`,
      okType: 'danger',
      onOk: () => {
        setRules(rules.filter(rule => !selectedRuleKeys.includes(rule.id)));
        setSelectedRuleKeys([]);
        message.success(`${selectedRuleKeys.length} rules deleted`);
      },
    });
  };

  const handleRuleSubmit = async (values: any) => {
    setLoading(true);
    try {
      if (selectedRule) {
        const updatedRules = rules.map(rule => 
          rule.id === selectedRule.id 
            ? { ...rule, ...values, updated_at: new Date().toISOString() }
            : rule
        );
        setRules(updatedRules);
        message.success('Rule updated successfully');
      } else {
        const newRule: BlacklistRule = {
          id: `${Date.now()}`,
          ...values,
          created_by: 'admin',
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
        };
        setRules([newRule, ...rules]);
        message.success('Rule added successfully');
      }
      setRuleModalVisible(false);
      ruleForm.resetFields();
      setSelectedRule(null);
    } finally {
      setLoading(false);
    }
  };

  const handleApplyRules = () => {
    setLoading(true);
    setTimeout(() => {
      message.success('Rules applied successfully. 5 buyers added to blacklist.');
      setLoading(false);
    }, 1500);
  };

  const handleViewRule = (rule: BlacklistRule) => {
    setSelectedRule(rule);
    // 这里可以打开规则详情模态框
    message.info('Rule details will be shown here');
  };

  const handleImportBlacklist = () => {
    message.info('Import functionality will be implemented here');
  };

  const handleExportBlacklist = () => {
    message.info('Export functionality will be implemented here');
  };

  const handleCreate = async (values: any) => {
    setLoading(true);
    try {
      const newBlacklist: BlacklistRecord = {
        id: `${Date.now()}`,
        tenant_id: 'tenant-001',
        shop_id: 'shop-001',
        business_type: 'TOC',
        buyer_id: `buyer-${Date.now()}`,
        buyer_name: values.buyer_name,
        buyer_email: values.buyer_email,
        buyer_phone: values.buyer_phone,
        platform: values.platform,
        platform_buyer_id: values.platform_buyer_id,
        blacklist_reason: values.blacklist_reason,
        blacklist_type: values.blacklist_type,
        risk_score: values.risk_score,
        blacklist_date: dayjs().format('YYYY-MM-DD'),
        expiry_date: values.expiry_date ? values.expiry_date.format('YYYY-MM-DD') : undefined,
        status: 'ACTIVE',
        evidence: values.evidence,
        created_by: 'admin',
        trace_id: `trace-${Date.now()}`,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };

      setBlacklists([newBlacklist, ...blacklists]);
      message.success('Buyer added to blacklist successfully');
      setCreateModalVisible(false);
      form.resetFields();
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = async (values: any) => {
    if (!selectedBlacklist) return;

    setLoading(true);
    try {
      const updatedBlacklists = blacklists.map(bl => 
        bl.id === selectedBlacklist.id 
          ? {
              ...bl,
              buyer_name: values.buyer_name,
              buyer_email: values.buyer_email,
              buyer_phone: values.buyer_phone,
              blacklist_reason: values.blacklist_reason,
              blacklist_type: values.blacklist_type,
              risk_score: values.risk_score,
              expiry_date: values.expiry_date ? values.expiry_date.format('YYYY-MM-DD') : undefined,
              status: values.status,
              evidence: values.evidence,
              updated_at: new Date().toISOString(),
            }
          : bl
      );

      setBlacklists(updatedBlacklists);
      message.success('Blacklist record updated successfully');
      setEditModalVisible(false);
      form.resetFields();
      setSelectedBlacklist(null);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: 'Remove from Blacklist',
      content: 'Are you sure you want to remove this buyer from the blacklist?',
      okType: 'danger',
      onOk: () => {
        const updatedBlacklists = blacklists.map(bl => 
          bl.id === id ? { ...bl, status: 'INACTIVE' as const, updated_at: new Date().toISOString() } : bl
        );
        setBlacklists(updatedBlacklists);
        message.success('Buyer removed from blacklist');
      },
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('Please select records to delete');
      return;
    }

    Modal.confirm({
      title: 'Batch Remove from Blacklist',
      content: `Are you sure you want to remove ${selectedRowKeys.length} buyers from the blacklist?`,
      okType: 'danger',
      onOk: () => {
        const updatedBlacklists = blacklists.map(bl => 
          selectedRowKeys.includes(bl.id) ? { ...bl, status: 'INACTIVE' as const, updated_at: new Date().toISOString() } : bl
        );
        setBlacklists(updatedBlacklists);
        setSelectedRowKeys([]);
        message.success(`${selectedRowKeys.length} buyers removed from blacklist`);
      },
    });
  };

  const handleViewDetail = (blacklist: BlacklistRecord) => {
    setSelectedBlacklist(blacklist);
    setDetailModalVisible(true);
  };

  const handleEditClick = (blacklist: BlacklistRecord) => {
    setSelectedBlacklist(blacklist);
    form.setFieldsValue({
      buyer_name: blacklist.buyer_name,
      buyer_email: blacklist.buyer_email,
      buyer_phone: blacklist.buyer_phone,
      platform: blacklist.platform,
      platform_buyer_id: blacklist.platform_buyer_id,
      blacklist_reason: blacklist.blacklist_reason,
      blacklist_type: blacklist.blacklist_type,
      risk_score: blacklist.risk_score,
      expiry_date: blacklist.expiry_date ? dayjs(blacklist.expiry_date) : null,
      status: blacklist.status,
      evidence: blacklist.evidence,
    });
    setEditModalVisible(true);
  };

  const getFilteredBlacklists = () => {
    let filtered = blacklists;

    if (activeTab !== 'all') {
      filtered = filtered.filter(bl => bl.status === activeTab.toUpperCase());
    }

    if (searchText) {
      filtered = filtered.filter(bl => 
        bl.buyer_name.toLowerCase().includes(searchText.toLowerCase()) ||
        bl.buyer_email.toLowerCase().includes(searchText.toLowerCase()) ||
        bl.platform_buyer_id.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    if (platformFilter) {
      filtered = filtered.filter(bl => bl.platform === platformFilter);
    }

    if (typeFilter) {
      filtered = filtered.filter(bl => bl.blacklist_type === typeFilter);
    }

    return filtered;
  };

  const getRiskLevel = (score: number): { level: string; color: string } => {
    if (score >= 80) return { level: 'Critical', color: '#ff4d4f' };
    if (score >= 60) return { level: 'High', color: '#ff7a45' };
    if (score >= 40) return { level: 'Medium', color: '#faad14' };
    return { level: 'Low', color: '#52c41a' };
  };

  const columns: ColumnsType<BlacklistRecord> = [
    {
      title: 'Buyer Name',
      dataIndex: 'buyer_name',
      key: 'buyer_name',
      width: 150,
      render: (name: string, record: BlacklistRecord) => (
        <a onClick={() => handleViewDetail(record)}>{name}</a>
      ),
    },
    {
      title: 'Email',
      dataIndex: 'buyer_email',
      key: 'buyer_email',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
    },
    {
      title: 'Platform Buyer ID',
      dataIndex: 'platform_buyer_id',
      key: 'platform_buyer_id',
      width: 150,
    },
    {
      title: 'Type',
      dataIndex: 'blacklist_type',
      key: 'blacklist_type',
      width: 100,
      render: (type: string) => {
        const config = BLACKLIST_TYPES.find(t => t.value === type);
        return <Tag color={config?.color}>{type}</Tag>;
      },
    },
    {
      title: 'Risk Score',
      dataIndex: 'risk_score',
      key: 'risk_score',
      width: 120,
      render: (score: number) => {
        const { level, color } = getRiskLevel(score);
        return (
          <Tag color={color}>
            {score} - {level}
          </Tag>
        );
      },
      sorter: (a, b) => a.risk_score - b.risk_score,
    },
    {
      title: 'Blacklist Date',
      dataIndex: 'blacklist_date',
      key: 'blacklist_date',
      width: 120,
    },
    {
      title: 'Expiry Date',
      dataIndex: 'expiry_date',
      key: 'expiry_date',
      width: 120,
      render: (date: string) => {
        if (!date) return '-';
        const daysUntilExpiry = dayjs(date).diff(dayjs(), 'day');
        const isExpiringSoon = daysUntilExpiry > 0 && daysUntilExpiry <= 30;
        return (
          <Tooltip title={isExpiringSoon ? `Expires in ${daysUntilExpiry} days` : ''}>
            <span style={{ color: isExpiringSoon || daysUntilExpiry <= 0 ? '#ff4d4f' : undefined }}>
              {date}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = STATUS_CONFIG[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      render: (_, record: BlacklistRecord) => (
        <Space>
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          <Tooltip title="Edit">
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEditClick(record)} />
          </Tooltip>
          {record.status === 'ACTIVE' && (
            <Tooltip title="Remove">
              <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  const stats = {
    total: blacklists.length,
    active: blacklists.filter(bl => bl.status === 'ACTIVE').length,
    inactive: blacklists.filter(bl => bl.status === 'INACTIVE').length,
    expired: blacklists.filter(bl => bl.status === 'EXPIRED').length,
    highRisk: blacklists.filter(bl => bl.risk_score >= 60).length,
  };

  const tabItems = [
    {
      key: 'blacklist',
      label: 'Blacklist Records',
      children: (
        <Card title="Blacklist Management" extra={
          <Space>
            <Button icon={<FileExcelOutlined />} onClick={handleImportBlacklist}>
              Import
            </Button>
            <Button icon={<FileTextOutlined />} onClick={handleExportBlacklist}>
              Export
            </Button>
            {selectedRowKeys.length > 0 && (
              <Button danger icon={<DeleteOutlined />} onClick={handleBatchDelete}>
                Batch Remove ({selectedRowKeys.length})
              </Button>
            )}
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
              Add to Blacklist
            </Button>
          </Space>
        }>
          <div style={{ display: 'flex', marginBottom: 16, gap: 16 }}>
            <Input
              placeholder="Search by name, email, or platform buyer ID"
              prefix={<SearchOutlined />}
              style={{ width: 300 }}
              onChange={(e) => setSearchText(e.target.value)}
            />
            <Select
              placeholder="Filter by Platform"
              style={{ width: 150 }}
              onChange={setPlatformFilter}
              allowClear
            >
              {PLATFORMS.map(platform => (
                <Option key={platform} value={platform}>{platform}</Option>
              ))}
            </Select>
            <Select
              placeholder="Filter by Type"
              style={{ width: 150 }}
              onChange={setTypeFilter}
              allowClear
            >
              {BLACKLIST_TYPES.map(type => (
                <Option key={type.value} value={type.value}>{type.label}</Option>
              ))}
            </Select>
          </div>

          <Tabs activeKey={activeTab} onChange={setActiveTab} items={[
            { key: 'all', label: 'All' },
            { key: 'active', label: 'Active' },
            { key: 'inactive', label: 'Inactive' },
            { key: 'expired', label: 'Expired' },
          ]} />

          <Table
            columns={columns}
            dataSource={getFilteredBlacklists()}
            rowKey="id"
            loading={loading}
            rowSelection={{
              selectedRowKeys,
              onChange: setSelectedRowKeys,
              getCheckboxProps: (record) => ({
                disabled: record.status !== 'ACTIVE',
              }),
            }}
            pagination={{ pageSize: 10 }}
          />
        </Card>
      ),
    },
    {
      key: 'rules',
      label: 'Blacklist Rules',
      children: (
        <Card title="Blacklist Rule Engine" extra={
          <Space>
            <Button icon={<RestOutlined />} onClick={fetchRules}>
              Refresh
            </Button>
            <Button icon={<PlayCircleOutlined />} onClick={handleApplyRules}>
              Apply Rules
            </Button>
            {selectedRuleKeys.length > 0 && (
              <Button danger icon={<DeleteOutlined />} onClick={handleBatchDeleteRules}>
                Batch Delete ({selectedRuleKeys.length})
              </Button>
            )}
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddRule}>
              Add Rule
            </Button>
          </Space>
        }>
          <div style={{ marginBottom: 16 }}>
            <Alert
              message="Rule Engine"
              description="Create and manage rules to automatically blacklist high-risk buyers based on their behavior and transaction patterns."
              type="info"
              showIcon
              icon={<BulbOutlined />}
            />
          </div>

          <Tabs activeKey={activeRuleTab} onChange={setActiveRuleTab} items={[
            { key: 'rules', label: 'Rules' },
            { key: 'logs', label: 'Rule Logs' },
          ]} />

          <Table
            columns={[
              {
                title: 'Name',
                dataIndex: 'name',
                key: 'name',
              },
              {
                title: 'Description',
                dataIndex: 'description',
                key: 'description',
              },
              {
                title: 'Condition Type',
                dataIndex: 'condition_type',
                key: 'condition_type',
                render: (type: string) => {
                  const config = RULE_CONDITIONS.find(c => c.value === type);
                  return <Tag>{config?.label}</Tag>;
                },
              },
              {
                title: 'Threshold',
                dataIndex: 'threshold',
                key: 'threshold',
              },
              {
                title: 'Risk Score',
                dataIndex: 'risk_score',
                key: 'risk_score',
                render: (score: number) => {
                  const { level, color } = getRiskLevel(score);
                  return (
                    <Tag color={color}>
                      {score} - {level}
                    </Tag>
                  );
                },
              },
              {
                title: 'Status',
                dataIndex: 'enabled',
                key: 'enabled',
                render: (enabled: boolean) => {
                  const status = enabled ? 'enabled' : 'disabled';
                  const config = RULE_STATUS.find(s => s.value === status);
                  return <Tag color={config?.color}>{config?.label}</Tag>;
                },
              },
              {
                title: 'Created At',
                dataIndex: 'created_at',
                key: 'created_at',
              },
              {
                title: 'Updated At',
                dataIndex: 'updated_at',
                key: 'updated_at',
              },
              {
                title: 'Actions',
                key: 'actions',
                render: (_, record) => (
                  <Space size="small">
                    <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewRule(record)} />
                    <Button type="link" icon={<EditOutlined />} onClick={() => handleEditRule(record)} />
                    <Button 
                      type="link" 
                      icon={record.enabled ? <PauseCircleOutlined /> : <PlayCircleOutlined />} 
                      onClick={() => handleToggleRule(record.id)}
                    />
                    <Popconfirm
                      title="Are you sure?"
                      description="This will delete the rule."
                      onConfirm={() => handleDeleteRule(record.id)}
                      okText="Delete"
                      cancelText="Cancel"
                    >
                      <Button type="link" danger icon={<DeleteOutlined />} />
                    </Popconfirm>
                  </Space>
                ),
              },
            ]}
            dataSource={rules}
            rowKey="id"
            loading={rulesLoading}
            rowSelection={{
              selectedRowKeys: selectedRuleKeys,
              onChange: setSelectedRuleKeys,
            }}
            pagination={{ pageSize: 10 }}
          />
        </Card>
      ),
    },
    {
      key: 'analytics',
      label: 'Risk Analysis',
      children: (
        <Card title="Risk Analysis Dashboard" extra={
          <Button icon={<RestOutlined />}>
            Refresh
          </Button>
        }>
          <div style={{ marginBottom: 16 }}>
            <Alert
              message="Risk Analysis"
              description="Analyze blacklist patterns and risk trends to improve your fraud prevention strategy."
              type="info"
              showIcon
              icon={<WarningOutlined />}
            />
          </div>

          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={8}>
              <Card>
                <h3 style={{ marginBottom: 16 }}><PieChartOutlined /> Risk Distribution</h3>
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f5f5f5' }}>
                  <div style={{ textAlign: 'center' }}>
                    <p>📊 Risk Distribution Chart</p>
                    <p>High: 45%</p>
                    <p>Medium: 30%</p>
                    <p>Low: 25%</p>
                  </div>
                </div>
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <h3 style={{ marginBottom: 16 }}><BarChartOutlined /> Blacklist by Type</h3>
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f5f5f5' }}>
                  <div style={{ textAlign: 'center' }}>
                    <p>📊 Blacklist Type Chart</p>
                    <p>FRAUD: 15</p>
                    <p>CHARGEBACK: 10</p>
                    <p>ABUSE: 8</p>
                    <p>OTHER: 5</p>
                  </div>
                </div>
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <h3 style={{ marginBottom: 16 }}><LineChartOutlined /> Risk Trend</h3>
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f5f5f5' }}>
                  <div style={{ textAlign: 'center' }}>
                    <p>📈 Risk Trend Chart</p>
                    <p>Jan: 20</p>
                    <p>Feb: 25</p>
                    <p>Mar: 30</p>
                    <p>Apr: 22</p>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>

          <Card>
            <h3 style={{ marginBottom: 16 }}>Risk Analysis Insights</h3>
            <div style={{ padding: 16, backgroundColor: '#f0f2f5', borderRadius: 8 }}>
              <h4>Key Insights:</h4>
              <ul style={{ marginLeft: 20, marginTop: 12 }}>
                <li>Most blacklisted buyers are from the Amazon platform (60%)</li>
                <li>Fraud-related blacklists have the highest average risk score (85)</li>
                <li>Chargeback rates have increased by 15% in the last quarter</li>
                <li>High-risk buyers are 3x more likely to have multiple blacklist entries</li>
              </ul>
              <h4 style={{ marginTop: 16 }}>Recommendations:</h4>
              <ul style={{ marginLeft: 20, marginTop: 12 }}>
                <li>Enhance fraud detection rules for high-risk platforms</li>
                <li>Implement stricter verification for buyers with chargeback history</li>
                <li>Review and update blacklist rules every 30 days</li>
                <li>Monitor new blacklist entries daily for pattern changes</li>
              </ul>
            </div>
          </Card>
        </Card>
      ),
    },
  ];

  return (
    <div className="blacklist-manage-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic title="Total Blacklisted" value={stats.total} prefix={<UserOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Active" value={stats.active} valueStyle={{ color: '#ff4d4f' }} prefix={<StopOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Inactive" value={stats.inactive} valueStyle={{ color: '#8c8c8c' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="High Risk" value={stats.highRisk} valueStyle={{ color: '#ff7a45' }} prefix={<WarningOutlined />} />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Alert
              message="Blacklist Alert"
              description={`${stats.active} buyers are currently blacklisted. ${stats.highRisk} are high risk.`}
              type="error"
              showIcon
              icon={<WarningOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Tabs defaultActiveKey="blacklist" style={{ marginBottom: 24 }} items={tabItems} />
    </div>
  );
};

export default BlacklistManage;

