import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Select,
  DatePicker,
  Descriptions,
  Divider,
  message,
  Tag,
  Tabs,
  Row,
  Col,
  Statistic,
  Alert,
  Tooltip,
  Progress,
  Badge,
  List,
  Empty,
  EyeOutlined,
  SearchOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  ThunderboltOutlined,
  SafetyOutlined,
  RadarChartOutlined,
  LineChartOutlined,
  BarChartOutlined,
  DashboardOutlined,
  FilterOutlined,
  ReloadOutlined,
  Option,
  RangePicker,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { blacklistDataSource, RiskAssessment } from '@/services/blacklistDataSource';

interface RiskAssessmentFormData {
  tenant_id: string;
  shop_id: string;
  buyer_id: string;
  platform: string;
  platform_buyer_id: string;
  risk_score: number;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  risk_factors: string[];
  recommendations: string[];
  is_blacklisted: boolean;
  blacklist_reasons?: string[];
  confidence_score: number;
  assessment_reason: string;
  assessment_date: string;
  created_at: string;
}

interface RiskStatistics {
  total_assessments: number;
  high_risk_count: number;
  medium_risk_count: number;
  low_risk_count: number;
  critical_risk_count: number;
  blacklist_conversion_rate: number;
  false_positives: number;
  false_negatives: number;
  by_platform: Record<string, number>;
  by_risk_level: Record<string, number>;
  average_risk_score: number;
  risk_trend: {
    date: string;
    average_score: number;
  }[];
}

const RISK_LEVEL_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode; percentage: number }> = {
  LOW: { color: 'success', text: 'Low', icon: <CheckCircleOutlined />, percentage: 25 },
  MEDIUM: { color: 'warning', text: 'Medium', icon: <ExclamationCircleOutlined />, percentage: 50 },
  HIGH: { color: 'error', text: 'High', icon: <WarningOutlined />, percentage: 75 },
  CRITICAL: { color: 'red', text: 'Critical', icon: <CloseCircleOutlined />, percentage: 100 },
};

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

const MOCK_ASSESSMENTS: RiskAssessment[] = [
  {
    id: '1',
    orderId: 'ORD-2026-001',
    customerId: 'CUST-001',
    customerName: 'Suspicious Customer',
    riskScore: 85,
    riskLevel: 'HIGH',
    riskFactors: ['新账户', '高额订单', '异常地址'],
    status: 'PENDING',
    createdAt: '2026-03-15',
    updatedAt: '2026-03-15',
  },
  {
    id: '2',
    orderId: 'ORD-2026-002',
    customerId: 'CUST-002',
    customerName: 'John Doe',
    riskScore: 45,
    riskLevel: 'MEDIUM',
    riskFactors: ['中等退货率', '新账户'],
    status: 'REVIEWING',
    createdAt: '2026-03-16',
    updatedAt: '2026-03-16',
  },
  {
    id: '3',
    orderId: 'ORD-2026-003',
    customerId: 'CUST-003',
    customerName: 'Jane Smith',
    riskScore: 15,
    riskLevel: 'LOW',
    riskFactors: [],
    status: 'APPROVED',
    reviewedBy: 'admin',
    reviewedAt: '2026-03-17',
    createdAt: '2026-03-17',
    updatedAt: '2026-03-17',
  },
  {
    id: '4',
    orderId: 'ORD-2026-004',
    customerId: 'CUST-004',
    customerName: 'Robert Johnson',
    riskScore: 90,
    riskLevel: 'CRITICAL',
    riskFactors: ['多次退款', '欺诈行为', '异常IP地址'],
    status: 'REJECTED',
    reviewedBy: 'admin',
    reviewedAt: '2026-03-18',
    createdAt: '2026-03-18',
    updatedAt: '2026-03-18',
  },
  {
    id: '5',
    orderId: 'ORD-2026-005',
    customerId: 'CUST-005',
    customerName: 'Alice Brown',
    riskScore: 30,
    riskLevel: 'LOW',
    riskFactors: ['轻微异常行为'],
    status: 'PENDING',
    createdAt: '2026-03-19',
    updatedAt: '2026-03-19',
  },
];

const MOCK_STATISTICS: RiskStatistics = {
  total_assessments: 150,
  high_risk_count: 35,
  medium_risk_count: 60,
  low_risk_count: 45,
  critical_risk_count: 10,
  blacklist_conversion_rate: 12.5,
  false_positives: 3,
  false_negatives: 1,
  by_platform: {
    'Amazon': 60,
    'eBay': 35,
    'Shopify': 25,
    'Walmart': 15,
    'TikTok Shop': 10,
    'Temu': 5,
  },
  by_risk_level: {
    'LOW': 45,
    'MEDIUM': 60,
    'HIGH': 35,
    'CRITICAL': 10,
  },
  average_risk_score: 42.5,
  risk_trend: [
    { date: '2026-03-12', average_score: 38.2 },
    { date: '2026-03-13', average_score: 40.5 },
    { date: '2026-03-14', average_score: 39.8 },
    { date: '2026-03-15', average_score: 41.2 },
    { date: '2026-03-16', average_score: 43.5 },
    { date: '2026-03-17', average_score: 42.1 },
    { date: '2026-03-18', average_score: 42.5 },
  ],
};

const RiskMonitor: FC = () => {
  const [loading, setLoading] = useState(false);
  const [assessments, setAssessments] = useState<RiskAssessment[]>(MOCK_ASSESSMENTS);
  const [statistics, setStatistics] = useState<RiskStatistics>(MOCK_STATISTICS);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedAssessment, setSelectedAssessment] = useState<RiskAssessment | null>(null);
  const [activeTab, setActiveTab] = useState('all');
  const [platformFilter, setPlatformFilter] = useState<string>('');
  const [riskLevelFilter, setRiskLevelFilter] = useState<string>('');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);

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

  const fetchRiskData = async () => {
    setLoading(true);
    try {
      setAssessments(MOCK_ASSESSMENTS);
      setStatistics(MOCK_STATISTICS);
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (assessment: RiskAssessment) => {
    setSelectedAssessment(assessment);
    setDetailModalVisible(true);
  };

  const getFilteredAssessments = () => {
    let filtered = assessments;

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

    if (riskLevelFilter) {
      filtered = filtered.filter(a => a.riskLevel === riskLevelFilter.toUpperCase());
    }

    if (dateRange) {
      filtered = filtered.filter(a => {
        const assessmentDate = dayjs(a.createdAt);
        return assessmentDate.isAfter(dateRange[0].startOf('day')) &&
               assessmentDate.isBefore(dateRange[1].endOf('day'));
      });
    }

    return filtered;
  };

  const getRiskColor = (score: number): string => {
    if (score >= 80) return '#ff4d4f';
    if (score >= 60) return '#ff7a45';
    if (score >= 40) return '#faad14';
    return '#52c41a';
  };

  const columns: ColumnsType<RiskAssessment> = [
    {
      title: 'Order ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 150,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 150,
      render: (name: string, record: RiskAssessment) => (
        <div>
          <div style={{ fontWeight: 500 }}>{name}</div>
          <div style={{ fontSize: 12, color: '#999' }}>{record.customerId}</div>
        </div>
      ),
    },
    {
      title: 'Risk Score',
      dataIndex: 'riskScore',
      key: 'riskScore',
      width: 150,
      render: (score: number, record: RiskAssessment) => (
        <div>
          <Progress
            percent={score}
            strokeColor={getRiskColor(score)}
            size="small"
            format={percent => `${percent}`}
          />
          <Tag color={getRiskColor(score)} style={{ marginTop: 4 }}>
            {record.riskLevel}
          </Tag>
        </div>
      ),
      sorter: (a, b) => a.riskScore - b.riskScore,
    },
    {
      title: 'Risk Factors',
      dataIndex: 'riskFactors',
      key: 'riskFactors',
      width: 200,
      render: (factors: string[]) => (
        <div>
          {factors.slice(0, 2).map((factor, index) => (
            <Tag key={index} color="orange" style={{ marginBottom: 2 }}>
              {factor}
            </Tag>
          ))}
          {factors.length > 2 && (
            <Tooltip title={factors.slice(2).join(', ')}>
              <Tag color="default">+{factors.length - 2} more</Tag>
            </Tooltip>
          )}
        </div>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={
          status === 'PENDING' ? 'blue' : 
          status === 'REVIEWING' ? 'orange' : 
          status === 'APPROVED' ? 'green' : 'red'
        }>
          {status === 'PENDING' ? 'Pending' : 
           status === 'REVIEWING' ? 'Reviewing' : 
           status === 'APPROVED' ? 'Approved' : 'Rejected'}
        </Tag>
      ),
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 80,
      render: (_, record: RiskAssessment) => (
        <Tooltip title="View Details">
          <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
        </Tooltip>
      ),
    },
  ];

  const highRiskAlerts = assessments.filter(a => a.riskLevel === 'HIGH' || a.riskLevel === 'CRITICAL');

  return (
    <div className="risk-monitor-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="Total Assessments"
              value={statistics.total_assessments}
              prefix={<DashboardOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Critical Risk"
              value={statistics.critical_risk_count}
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="High Risk"
              value={statistics.high_risk_count}
              valueStyle={{ color: '#ff7a45' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Medium Risk"
              value={statistics.medium_risk_count}
              valueStyle={{ color: '#faad14' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Low Risk"
              value={statistics.low_risk_count}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Avg Risk Score"
              value={statistics.average_risk_score}
              precision={1}
              valueStyle={{ color: '#1890ff' }}
              prefix={<RadarChartOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="Risk Distribution" extra={<BarChartOutlined />}>
            <div style={{ marginTop: 16 }}>
              {Object.entries(statistics.by_risk_level).map(([level, count]) => {
                const config = RISK_LEVEL_CONFIG[level];
                const percentage = statistics.total_assessments > 0 
                  ? (count / statistics.total_assessments) * 100 
                  : 0;
                return (
                  <div key={level} style={{ marginBottom: 16 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span>
                        <Tag color={config.color} icon={config.icon}>{config.text}</Tag>
                        <span style={{ marginLeft: 8 }}>{count} assessments</span>
                      </span>
                      <span>{percentage.toFixed(1)}%</span>
                    </div>
                    <Progress
                      percent={percentage}
                      strokeColor={config.color}
                      showInfo={false}
                    />
                  </div>
                );
              })}
            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="Risk by Platform" extra={<ThunderboltOutlined />}>
            <List
              dataSource={Object.entries(statistics.by_platform)
                .sort(([, a], [, b]) => b - a)
                .slice(0, 6)}
              renderItem={([platform, count]) => (
                <List.Item key={platform}>
                  <List.Item.Meta
                    title={platform}
                    description={`${count} assessments`}
                  />
                  <Progress
                    percent={statistics.total_assessments > 0 ? (count / statistics.total_assessments) * 100 : 0}
                    strokeColor="#1890ff"
                    style={{ width: 150 }}
                    showInfo={false}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {highRiskAlerts.length > 0 && (
        <Card 
          title={
            <Space>
              <WarningOutlined style={{ color: '#ff4d4f' }} />
              <span>High Risk Alerts</span>
              <Badge count={highRiskAlerts.length} style={{ backgroundColor: '#ff4d4f' }} />
            </Space>
          }
          style={{ marginBottom: 24 }}
        >
          <Alert
            message={`${highRiskAlerts.length} buyers identified as high or critical risk`}
            description="Immediate action recommended for critical risk buyers"
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <List
            dataSource={highRiskAlerts.slice(0, 5)}
            renderItem={(assessment) => (
              <List.Item
                actions={[
                  <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(assessment)}>
                    View Details
                  </Button>
                ]}
              >
                <List.Item.Meta
                  title={
                    <Space>
                      <span>{assessment.platform || '-'}</span>
                      <span>{assessment.platform_buyer_id || '-'}</span>
                      <Tag color={getRiskColor(assessment.riskScore || assessment.risk_score || 0)}>{assessment.riskLevel || assessment.risk_level}</Tag>
                    </Space>
                  }
                  description={`Risk Score: ${assessment.riskScore || assessment.risk_score || 0} | ${dayjs(assessment.assessment_date || assessment.createdAt).format('YYYY-MM-DD HH:mm')}`}
                />
              </List.Item>
            )}
          />
        </Card>
      )}

      <Card 
        title="Risk Assessment History" 
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchRiskData}>Refresh</Button>
          </Space>
        }
      >
        <div style={{ display: 'flex', marginBottom: 16, gap: 16, flexWrap: 'wrap' }}>
          <Select
            placeholder="Filter by Risk Level"
            style={{ width: 150 }}
            onChange={setRiskLevelFilter}
            allowClear
            suffixIcon={<FilterOutlined />}
          >
            {Object.entries(RISK_LEVEL_CONFIG).map(([level, config]) => (
              <Option key={level} value={level}>
                <Tag color={config.color} icon={config.icon}>{config.text}</Tag>
              </Option>
            ))}
          </Select>
          <RangePicker
            style={{ width: 300 }}
            onChange={(dates) => setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs] | null)}
          />
        </div>

        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={[
            { key: 'all', label: 'All' },
            { key: 'critical', label: <Badge count={statistics.critical_risk_count} offset={[10, 0]} size="small">Critical</Badge> },
            { key: 'high', label: <Badge count={statistics.high_risk_count} offset={[10, 0]} size="small">High</Badge> },
            { key: 'medium', label: 'Medium' },
            { key: 'low', label: 'Low' },
          ]}
        />

        <Table
          columns={columns}
          dataSource={getFilteredAssessments()}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
          locale={{
            emptyText: (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="No risk assessments found"
              />
            ),
          }}
        />
      </Card>

      <Modal
        title="Risk Assessment Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>Close</Button>,
        ]}
        width={800}
      >
        {selectedAssessment && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Order ID">{selectedAssessment.orderId}</Descriptions.Item>
              <Descriptions.Item label="Customer ID">{selectedAssessment.customerId}</Descriptions.Item>
              <Descriptions.Item label="Customer Name">{selectedAssessment.customerName}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={
                  selectedAssessment.status === 'PENDING' ? 'blue' : 
                  selectedAssessment.status === 'REVIEWING' ? 'orange' : 
                  selectedAssessment.status === 'APPROVED' ? 'green' : 'red'
                }>
                  {selectedAssessment.status === 'PENDING' ? 'Pending' : 
                   selectedAssessment.status === 'REVIEWING' ? 'Reviewing' : 
                   selectedAssessment.status === 'APPROVED' ? 'Approved' : 'Rejected'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Risk Score">
                <Progress
                  percent={selectedAssessment.riskScore}
                  strokeColor={getRiskColor(selectedAssessment.riskScore)}
                  format={percent => `${percent}`}
                />
              </Descriptions.Item>
              <Descriptions.Item label="Risk Level">
                <Tag color={getRiskColor(selectedAssessment.riskScore)} icon={RISK_LEVEL_CONFIG[selectedAssessment.riskLevel].icon}>
                  {RISK_LEVEL_CONFIG[selectedAssessment.riskLevel].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Created At" span={2}>
                {dayjs(selectedAssessment.createdAt).format('YYYY-MM-DD')}
              </Descriptions.Item>
              {selectedAssessment.reviewedAt && (
                <Descriptions.Item label="Reviewed At" span={2}>
                  {dayjs(selectedAssessment.reviewedAt).format('YYYY-MM-DD')}
                </Descriptions.Item>
              )}
              {selectedAssessment.reviewedBy && (
                <Descriptions.Item label="Reviewed By" span={2}>{selectedAssessment.reviewedBy}</Descriptions.Item>
              )}
            </Descriptions>

            <Divider>Risk Factors</Divider>
            {selectedAssessment.riskFactors.length > 0 ? (
              <Space wrap>
                {selectedAssessment.riskFactors.map((factor, index) => (
                  <Tag key={index} color="orange">{factor}</Tag>
                ))}
              </Space>
            ) : (
              <Empty description="No risk factors identified" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default RiskMonitor;
