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

const { Option } = Select;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

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',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-001',
    platform: 'Amazon',
    platform_buyer_id: 'AMZ-001',
    risk_score: 85,
    risk_level: 'CRITICAL',
    risk_factors: ['High return rate', 'Multiple chargebacks', 'Suspicious activity'],
    recommendations: ['Block buyer immediately', 'Add to blacklist', 'Review all past transactions'],
    is_blacklisted: true,
    blacklist_reasons: ['Fraudulent transactions'],
    confidence_score: 85,
    assessment_reason: 'New order received',
    assessment_date: '2026-03-18 10:30:00',
    created_at: '2026-03-18 10:30:00',
  },
  {
    id: '2',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-002',
    platform: 'eBay',
    platform_buyer_id: 'EBAY-002',
    risk_score: 72,
    risk_level: 'HIGH',
    risk_factors: ['High return rate', 'New account'],
    recommendations: ['Place order on hold', 'Request additional verification', 'Limit order amount'],
    is_blacklisted: false,
    confidence_score: 78,
    assessment_reason: 'New order received',
    assessment_date: '2026-03-18 11:15:00',
    created_at: '2026-03-18 11:15:00',
  },
  {
    id: '3',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-003',
    platform: 'Amazon',
    platform_buyer_id: 'AMZ-003',
    risk_score: 45,
    risk_level: 'MEDIUM',
    risk_factors: ['Moderate return rate'],
    recommendations: ['Monitor transaction closely', 'Set lower order limits'],
    is_blacklisted: false,
    confidence_score: 65,
    assessment_reason: 'New order received',
    assessment_date: '2026-03-18 12:00:00',
    created_at: '2026-03-18 12:00:00',
  },
  {
    id: '4',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-004',
    platform: 'Shopify',
    platform_buyer_id: 'SHOPIFY-004',
    risk_score: 15,
    risk_level: 'LOW',
    risk_factors: [],
    recommendations: ['Process order normally', 'Continue monitoring'],
    is_blacklisted: false,
    confidence_score: 90,
    assessment_reason: 'New order received',
    assessment_date: '2026-03-18 12:30:00',
    created_at: '2026-03-18 12:30:00',
  },
  {
    id: '5',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-005',
    platform: 'Walmart',
    platform_buyer_id: 'WMT-005',
    risk_score: 65,
    risk_level: 'HIGH',
    risk_factors: ['Chargeback history', 'Multiple IP changes'],
    recommendations: ['Place order on hold', 'Use secure payment methods', 'Monitor future transactions'],
    is_blacklisted: true,
    blacklist_reasons: ['Excessive chargebacks'],
    confidence_score: 72,
    assessment_reason: 'New order received',
    assessment_date: '2026-03-18 13:00:00',
    created_at: '2026-03-18 13:00:00',
  },
];

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: React.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.risk_level === activeTab.toUpperCase());
    }

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

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

    if (dateRange) {
      filtered = filtered.filter(a => {
        const assessmentDate = dayjs(a.assessment_date);
        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: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
    },
    {
      title: 'Platform Buyer ID',
      dataIndex: 'platform_buyer_id',
      key: 'platform_buyer_id',
      width: 150,
    },
    {
      title: 'Risk Score',
      dataIndex: 'risk_score',
      key: 'risk_score',
      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.risk_level}
          </Tag>
        </div>
      ),
      sorter: (a, b) => a.risk_score - b.risk_score,
    },
    {
      title: 'Risk Factors',
      dataIndex: 'risk_factors',
      key: 'risk_factors',
      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: 'Blacklisted',
      dataIndex: 'is_blacklisted',
      key: 'is_blacklisted',
      width: 100,
      render: (isBlacklisted: boolean) => (
        <Tag color={isBlacklisted ? 'error' : 'success'} icon={isBlacklisted ? <CloseCircleOutlined /> : <CheckCircleOutlined />}>
          {isBlacklisted ? 'Yes' : 'No'}
        </Tag>
      ),
    },
    {
      title: 'Confidence',
      dataIndex: 'confidence_score',
      key: 'confidence_score',
      width: 100,
      render: (score: number) => (
        <Progress
          percent={score}
          strokeColor="#1890ff"
          size="small"
          format={percent => `${percent}%`}
        />
      ),
    },
    {
      title: 'Assessment Date',
      dataIndex: 'assessment_date',
      key: 'assessment_date',
      width: 150,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      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.risk_level === 'HIGH' || a.risk_level === '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.risk_score)}>{assessment.risk_level}</Tag>
                    </Space>
                  }
                  description={`Risk Score: ${assessment.risk_score} | ${dayjs(assessment.assessment_date).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 Platform"
            style={{ width: 150 }}
            onChange={setPlatformFilter}
            allowClear
            suffixIcon={<FilterOutlined />}
          >
            {PLATFORMS.map(platform => (
              <Option key={platform} value={platform}>{platform}</Option>
            ))}
          </Select>
          <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}>
          <TabPane tab="All" key="all" />
          <TabPane tab={<Badge count={statistics.critical_risk_count} offset={[10, 0]} size="small">Critical</Badge>} key="critical" />
          <TabPane tab={<Badge count={statistics.high_risk_count} offset={[10, 0]} size="small">High</Badge>} key="high" />
          <TabPane tab="Medium" key="medium" />
          <TabPane tab="Low" key="low" />
        </Tabs>

        <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="Platform">{selectedAssessment.platform}</Descriptions.Item>
              <Descriptions.Item label="Platform Buyer ID">{selectedAssessment.platform_buyer_id}</Descriptions.Item>
              <Descriptions.Item label="Risk Score">
                <Progress
                  percent={selectedAssessment.risk_score}
                  strokeColor={getRiskColor(selectedAssessment.risk_score)}
                  format={percent => `${percent}`}
                />
              </Descriptions.Item>
              <Descriptions.Item label="Risk Level">
                <Tag color={getRiskColor(selectedAssessment.risk_score)} icon={RISK_LEVEL_CONFIG[selectedAssessment.risk_level].icon}>
                  {RISK_LEVEL_CONFIG[selectedAssessment.risk_level].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Confidence Score">
                <Progress
                  percent={selectedAssessment.confidence_score}
                  strokeColor="#1890ff"
                  format={percent => `${percent}%`}
                />
              </Descriptions.Item>
              <Descriptions.Item label="Blacklisted">
                <Tag color={selectedAssessment.is_blacklisted ? 'error' : 'success'} icon={selectedAssessment.is_blacklisted ? <CloseCircleOutlined /> : <CheckCircleOutlined />}>
                  {selectedAssessment.is_blacklisted ? 'Yes' : 'No'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Assessment Reason" span={2}>{selectedAssessment.assessment_reason}</Descriptions.Item>
              <Descriptions.Item label="Assessment Date" span={2}>
                {dayjs(selectedAssessment.assessment_date).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
            </Descriptions>

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

            <Divider>Recommendations</Divider>
            {selectedAssessment.recommendations.length > 0 ? (
              <List
                dataSource={selectedAssessment.recommendations}
                renderItem={(recommendation, index) => (
                  <List.Item key={index}>
                    <SafetyOutlined style={{ color: '#1890ff', marginRight: 8 }} />
                    {recommendation}
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="No recommendations" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}

            {selectedAssessment.is_blacklisted && selectedAssessment.blacklist_reasons && (
              <>
                <Divider>Blacklist Reasons</Divider>
                <Space wrap>
                  {selectedAssessment.blacklist_reasons.map((reason, index) => (
                    <Tag key={index} color="error">{reason}</Tag>
                  ))}
                </Space>
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default RiskMonitor;
