/**
 * RiskDashboard Component - لوحة تحكم المخاطر
 */

import React, { useState, useEffect } from 'react';

interface RiskCustomer {
  customerId: string;
  customerName: string;
  defaultProbability: number;
  riskCategory: 'low' | 'medium' | 'high' | 'critical';
  riskChange: number;
  daysToDefault: number | null;
  topRiskFactor: string;
  recommendedAction: string;
  lastContact: string;
}

interface RiskStats {
  totalCustomers: number;
  byRisk: {
    low: number;
    medium: number;
    high: number;
    critical: number;
  };
  avgDefaultProbability: number;
  predictedDefaults: number;
  modelAccuracy: number;
}

interface Warning {
  id: string;
  customerId: string;
  type: string;
  level: 'info' | 'warning' | 'danger' | 'critical';
  message: string;
  createdAt: string;
}

export const RiskDashboard: React.FC = () => {
  const [customers, setCustomers] = useState<RiskCustomer[]>([]);
  const [stats, setStats] = useState<RiskStats | null>(null);
  const [warnings, setWarnings] = useState<Warning[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedRisk, setSelectedRisk] = useState<string>('all');

  useEffect(() => {
    loadData();
    const interval = setInterval(loadData, 60000);
    return () => clearInterval(interval);
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [customersRes, statsRes, warningsRes] = await Promise.all([
        fetch('/api/plugins/database-connector/predictions/high-risk'),
        fetch('/api/plugins/database-connector/predictions/stats'),
        fetch('/api/plugins/database-connector/warnings/active'),
      ]);

      if (customersRes.ok) setCustomers(await customersRes.json());
      if (statsRes.ok) setStats(await statsRes.json());
      if (warningsRes.ok) setWarnings(await warningsRes.json());
    } catch (error) {
      console.error('Error loading data:', error);
      // Use mock data for development
      setStats({
        totalCustomers: 445,
        byRisk: { low: 280, medium: 120, high: 35, critical: 10 },
        avgDefaultProbability: 0.32,
        predictedDefaults: 18,
        modelAccuracy: 0.83,
      });
      setCustomers([
        { customerId: 'C001', customerName: 'أحمد محمد', defaultProbability: 0.92, riskCategory: 'critical', riskChange: 15, daysToDefault: 14, topRiskFactor: 'وعود مكسورة', recommendedAction: 'escalate', lastContact: '2026-01-28' },
        { customerId: 'C002', customerName: 'سارة علي', defaultProbability: 0.78, riskCategory: 'high', riskChange: 8, daysToDefault: 30, topRiskFactor: 'تجنب الاتصال', recommendedAction: 'urgent_contact', lastContact: '2026-01-25' },
        { customerId: 'C003', customerName: 'محمد خالد', defaultProbability: 0.65, riskCategory: 'high', riskChange: -5, daysToDefault: 45, topRiskFactor: 'تأخر سداد', recommendedAction: 'contact', lastContact: '2026-01-29' },
      ]);
      setWarnings([
        { id: 'W1', customerId: 'C001', type: 'broken_promises', level: 'critical', message: 'وعود دفع مكسورة متعددة', createdAt: '2026-01-30T10:00:00Z' },
        { id: 'W2', customerId: 'C002', type: 'avoiding_contact', level: 'danger', message: 'العميل يتجنب التواصل', createdAt: '2026-01-30T09:30:00Z' },
      ]);
    }
    setLoading(false);
  };

  const getRiskColor = (risk: string) => {
    switch (risk) {
      case 'critical': return '#dc3545';
      case 'high': return '#fd7e14';
      case 'medium': return '#ffc107';
      case 'low': return '#28a745';
      default: return '#6c757d';
    }
  };

  const getRiskLabel = (risk: string) => {
    switch (risk) {
      case 'critical': return 'حرج';
      case 'high': return 'عالي';
      case 'medium': return 'متوسط';
      case 'low': return 'منخفض';
      default: return risk;
    }
  };

  const filteredCustomers = selectedRisk === 'all' 
    ? customers 
    : customers.filter(c => c.riskCategory === selectedRisk);

  if (loading && !stats) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
        <div>جاري التحميل...</div>
      </div>
    );
  }

  return (
    <div style={{ direction: 'rtl', padding: '24px', fontFamily: 'Segoe UI, Tahoma, sans-serif' }}>
      <h1 style={{ margin: '0 0 24px 0', color: '#2c3e50' }}>📊 لوحة تحكم المخاطر</h1>

      {/* Stats Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
        <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
          <div style={{ fontSize: '14px', color: '#666', marginBottom: '8px' }}>إجمالي العملاء</div>
          <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#2c3e50' }}>{stats?.totalCustomers || 0}</div>
        </div>
        
        <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
          <div style={{ fontSize: '14px', color: '#666', marginBottom: '8px' }}>عملاء عالي المخاطر</div>
          <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#dc3545' }}>
            {(stats?.byRisk.high || 0) + (stats?.byRisk.critical || 0)}
          </div>
        </div>
        
        <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
          <div style={{ fontSize: '14px', color: '#666', marginBottom: '8px' }}>متوقع تعثرهم</div>
          <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#fd7e14' }}>{stats?.predictedDefaults || 0}</div>
        </div>
        
        <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
          <div style={{ fontSize: '14px', color: '#666', marginBottom: '8px' }}>دقة النموذج</div>
          <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#28a745' }}>
            {((stats?.modelAccuracy || 0) * 100).toFixed(0)}%
          </div>
        </div>
      </div>

      {/* Risk Distribution */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px', marginBottom: '24px' }}>
        <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
          <h3 style={{ marginTop: 0 }}>توزيع المخاطر</h3>
          <div style={{ display: 'flex', gap: '8px', height: '40px', borderRadius: '8px', overflow: 'hidden' }}>
            {stats && (
              <>
                <div style={{ 
                  flex: stats.byRisk.low, 
                  background: '#28a745', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  color: 'white',
                  fontSize: '12px',
                }}>
                  {stats.byRisk.low}
                </div>
                <div style={{ 
                  flex: stats.byRisk.medium, 
                  background: '#ffc107', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  fontSize: '12px',
                }}>
                  {stats.byRisk.medium}
                </div>
                <div style={{ 
                  flex: stats.byRisk.high, 
                  background: '#fd7e14', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  color: 'white',
                  fontSize: '12px',
                }}>
                  {stats.byRisk.high}
                </div>
                <div style={{ 
                  flex: stats.byRisk.critical, 
                  background: '#dc3545', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  color: 'white',
                  fontSize: '12px',
                }}>
                  {stats.byRisk.critical}
                </div>
              </>
            )}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '12px', fontSize: '12px' }}>
            <span style={{ color: '#28a745' }}>🟢 منخفض</span>
            <span style={{ color: '#ffc107' }}>🟡 متوسط</span>
            <span style={{ color: '#fd7e14' }}>🟠 عالي</span>
            <span style={{ color: '#dc3545' }}>🔴 حرج</span>
          </div>
        </div>

        <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
          <h3 style={{ marginTop: 0 }}>التحذيرات النشطة</h3>
          {warnings.length === 0 ? (
            <div style={{ color: '#666', textAlign: 'center', padding: '20px' }}>لا توجد تحذيرات</div>
          ) : (
            <div style={{ maxHeight: '150px', overflow: 'auto' }}>
              {warnings.slice(0, 5).map(warning => (
                <div 
                  key={warning.id}
                  style={{
                    padding: '8px 12px',
                    marginBottom: '8px',
                    borderRadius: '4px',
                    borderRight: `4px solid ${getRiskColor(warning.level)}`,
                    background: '#f8f9fa',
                  }}
                >
                  <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{warning.message}</div>
                  <div style={{ fontSize: '12px', color: '#666' }}>
                    العميل: {warning.customerId}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Customer Risk Table */}
      <div style={{ background: 'white', borderRadius: '8px', padding: '20px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
          <h3 style={{ margin: 0 }}>العملاء حسب المخاطر</h3>
          <select 
            value={selectedRisk}
            onChange={(e) => setSelectedRisk(e.target.value)}
            style={{ padding: '8px 16px', borderRadius: '4px', border: '1px solid #ddd' }}
          >
            <option value="all">الكل</option>
            <option value="critical">حرج</option>
            <option value="high">عالي</option>
            <option value="medium">متوسط</option>
            <option value="low">منخفض</option>
          </select>
        </div>

        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ borderBottom: '2px solid #eee' }}>
              <th style={{ padding: '12px', textAlign: 'right' }}>العميل</th>
              <th style={{ padding: '12px', textAlign: 'right' }}>المخاطر</th>
              <th style={{ padding: '12px', textAlign: 'right' }}>الاحتمالية</th>
              <th style={{ padding: '12px', textAlign: 'right' }}>التغير</th>
              <th style={{ padding: '12px', textAlign: 'right' }}>أيام للتعثر</th>
              <th style={{ padding: '12px', textAlign: 'right' }}>السبب الرئيسي</th>
              <th style={{ padding: '12px', textAlign: 'right' }}>الإجراء</th>
            </tr>
          </thead>
          <tbody>
            {filteredCustomers.map(customer => (
              <tr key={customer.customerId} style={{ borderBottom: '1px solid #eee' }}>
                <td style={{ padding: '12px' }}>
                  <div style={{ fontWeight: 'bold' }}>{customer.customerName}</div>
                  <div style={{ fontSize: '12px', color: '#666' }}>{customer.customerId}</div>
                </td>
                <td style={{ padding: '12px' }}>
                  <span style={{
                    padding: '4px 12px',
                    borderRadius: '12px',
                    background: getRiskColor(customer.riskCategory),
                    color: 'white',
                    fontSize: '12px',
                  }}>
                    {getRiskLabel(customer.riskCategory)}
                  </span>
                </td>
                <td style={{ padding: '12px' }}>
                  <div style={{ 
                    width: '100%', 
                    height: '8px', 
                    background: '#eee', 
                    borderRadius: '4px',
                    overflow: 'hidden',
                  }}>
                    <div style={{
                      width: `${customer.defaultProbability * 100}%`,
                      height: '100%',
                      background: getRiskColor(customer.riskCategory),
                    }} />
                  </div>
                  <div style={{ fontSize: '12px', marginTop: '4px' }}>
                    {(customer.defaultProbability * 100).toFixed(1)}%
                  </div>
                </td>
                <td style={{ padding: '12px' }}>
                  <span style={{ color: customer.riskChange > 0 ? '#dc3545' : '#28a745' }}>
                    {customer.riskChange > 0 ? '↑' : '↓'} {Math.abs(customer.riskChange)}%
                  </span>
                </td>
                <td style={{ padding: '12px' }}>
                  {customer.daysToDefault ? `${customer.daysToDefault} يوم` : '-'}
                </td>
                <td style={{ padding: '12px', fontSize: '13px' }}>{customer.topRiskFactor}</td>
                <td style={{ padding: '12px' }}>
                  <button style={{
                    padding: '6px 12px',
                    background: customer.riskCategory === 'critical' ? '#dc3545' : '#3498db',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    fontSize: '12px',
                  }}>
                    {customer.recommendedAction === 'escalate' ? 'تصعيد' : 
                     customer.recommendedAction === 'urgent_contact' ? 'اتصال عاجل' : 'اتصال'}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default RiskDashboard;
