/**
 * AlertsManager Component - إدارة التنبيهات
 */

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

interface Alert {
  id: string;
  type: string;
  title: string;
  message: string;
  priority: 'critical' | 'high' | 'medium' | 'low';
  status: 'active' | 'acknowledged' | 'resolved';
  channels: string[];
  customerId?: string;
  createdAt: string;
}

interface AlertRule {
  id: string;
  name: string;
  type: 'realtime' | 'scheduled' | 'smart';
  trigger: string;
  priority: string;
  channels: string[];
  isActive: boolean;
}

export const AlertsManager: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'alerts' | 'rules' | 'settings'>('alerts');
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [rules, setRules] = useState<AlertRule[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState({ priority: '', status: '' });

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [alertsRes, rulesRes] = await Promise.all([
        fetch('/api/plugins/database-connector/alerts'),
        fetch('/api/plugins/database-connector/alerts/rules'),
      ]);
      
      if (alertsRes.ok) setAlerts(await alertsRes.json());
      if (rulesRes.ok) setRules(await rulesRes.json());
    } catch (error) {
      console.error('Error loading data:', error);
    }
    setLoading(false);
  };

  const acknowledgeAlert = async (alertId: string) => {
    try {
      await fetch(`/api/plugins/database-connector/alerts/${alertId}/acknowledge`, {
        method: 'POST',
      });
      loadData();
    } catch (error) {
      console.error('Error acknowledging alert:', error);
    }
  };

  const resolveAlert = async (alertId: string) => {
    try {
      await fetch(`/api/plugins/database-connector/alerts/${alertId}/resolve`, {
        method: 'POST',
      });
      loadData();
    } catch (error) {
      console.error('Error resolving alert:', error);
    }
  };

  const toggleRule = async (ruleId: string, active: boolean) => {
    try {
      await fetch(`/api/plugins/database-connector/alerts/rules/${ruleId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isActive: active }),
      });
      loadData();
    } catch (error) {
      console.error('Error toggling rule:', error);
    }
  };

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

  const getPriorityIcon = (priority: string) => {
    switch (priority) {
      case 'critical': return '🔴';
      case 'high': return '🟠';
      case 'medium': return '🟡';
      case 'low': return '🟢';
      default: return '⚪';
    }
  };

  const filteredAlerts = alerts.filter(alert => {
    if (filter.priority && alert.priority !== filter.priority) return false;
    if (filter.status && alert.status !== filter.status) return false;
    return true;
  });

  const renderAlerts = () => (
    <div className="alerts-list">
      <div className="filters" style={{ marginBottom: '16px', display: 'flex', gap: '12px' }}>
        <select 
          value={filter.priority} 
          onChange={(e) => setFilter({ ...filter, priority: e.target.value })}
          style={{ padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
        >
          <option value="">كل الأولويات</option>
          <option value="critical">حرج</option>
          <option value="high">عالي</option>
          <option value="medium">متوسط</option>
          <option value="low">منخفض</option>
        </select>
        
        <select 
          value={filter.status} 
          onChange={(e) => setFilter({ ...filter, status: e.target.value })}
          style={{ padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
        >
          <option value="">كل الحالات</option>
          <option value="active">نشط</option>
          <option value="acknowledged">تم الاستلام</option>
          <option value="resolved">تم الحل</option>
        </select>
      </div>

      {filteredAlerts.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px', color: '#666' }}>
          لا توجد تنبيهات
        </div>
      ) : (
        filteredAlerts.map(alert => (
          <div 
            key={alert.id}
            style={{
              background: 'white',
              border: `2px solid ${getPriorityColor(alert.priority)}`,
              borderRadius: '8px',
              padding: '16px',
              marginBottom: '12px',
              boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                  <span style={{ fontSize: '20px' }}>{getPriorityIcon(alert.priority)}</span>
                  <h3 style={{ margin: 0, color: '#333' }}>{alert.title}</h3>
                  <span style={{
                    padding: '2px 8px',
                    borderRadius: '12px',
                    fontSize: '12px',
                    background: alert.status === 'active' ? '#dc3545' : alert.status === 'acknowledged' ? '#ffc107' : '#28a745',
                    color: 'white',
                  }}>
                    {alert.status === 'active' ? 'نشط' : alert.status === 'acknowledged' ? 'تم الاستلام' : 'تم الحل'}
                  </span>
                </div>
                <p style={{ margin: '0 0 8px 0', color: '#666' }}>{alert.message}</p>
                <div style={{ fontSize: '12px', color: '#999' }}>
                  <span>{new Date(alert.createdAt).toLocaleString('ar-SA')}</span>
                  {alert.customerId && <span style={{ marginRight: '16px' }}>العميل: {alert.customerId}</span>}
                </div>
              </div>
              
              <div style={{ display: 'flex', gap: '8px' }}>
                {alert.status === 'active' && (
                  <button
                    onClick={() => acknowledgeAlert(alert.id)}
                    style={{
                      padding: '8px 16px',
                      background: '#ffc107',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: 'pointer',
                    }}
                  >
                    استلام
                  </button>
                )}
                {alert.status !== 'resolved' && (
                  <button
                    onClick={() => resolveAlert(alert.id)}
                    style={{
                      padding: '8px 16px',
                      background: '#28a745',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: 'pointer',
                    }}
                  >
                    حل
                  </button>
                )}
              </div>
            </div>
          </div>
        ))
      )}
    </div>
  );

  const renderRules = () => (
    <div className="rules-list">
      <table style={{ width: '100%', borderCollapse: 'collapse', background: 'white', borderRadius: '8px', overflow: 'hidden' }}>
        <thead>
          <tr style={{ background: '#34495e', color: 'white' }}>
            <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: 'center' }}>الحالة</th>
          </tr>
        </thead>
        <tbody>
          {rules.map(rule => (
            <tr key={rule.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: '12px' }}>{rule.name}</td>
              <td style={{ padding: '12px' }}>
                <span style={{
                  padding: '4px 8px',
                  borderRadius: '4px',
                  fontSize: '12px',
                  background: rule.type === 'realtime' ? '#17a2b8' : rule.type === 'scheduled' ? '#6c757d' : '#9b59b6',
                  color: 'white',
                }}>
                  {rule.type === 'realtime' ? 'فوري' : rule.type === 'scheduled' ? 'مجدول' : 'ذكي'}
                </span>
              </td>
              <td style={{ padding: '12px', fontSize: '12px', color: '#666' }}>{rule.trigger}</td>
              <td style={{ padding: '12px' }}>
                <span style={{ color: getPriorityColor(rule.priority) }}>
                  {getPriorityIcon(rule.priority)} {rule.priority}
                </span>
              </td>
              <td style={{ padding: '12px', fontSize: '12px' }}>{rule.channels.join(', ')}</td>
              <td style={{ padding: '12px', textAlign: 'center' }}>
                <label style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={rule.isActive}
                    onChange={(e) => toggleRule(rule.id, e.target.checked)}
                    style={{ width: '18px', height: '18px', cursor: 'pointer' }}
                  />
                </label>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  const renderSettings = () => (
    <div className="settings">
      <div style={{ background: 'white', borderRadius: '8px', padding: '24px', marginBottom: '16px' }}>
        <h3 style={{ marginTop: 0 }}>إعدادات البريد الإلكتروني</h3>
        <div style={{ display: 'grid', gap: '16px' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>SMTP Host</label>
            <input type="text" placeholder="smtp.example.com" style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>Port</label>
              <input type="number" placeholder="587" style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>From Address</label>
              <input type="email" placeholder="alerts@example.com" style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }} />
            </div>
          </div>
        </div>
      </div>

      <div style={{ background: 'white', borderRadius: '8px', padding: '24px', marginBottom: '16px' }}>
        <h3 style={{ marginTop: 0 }}>إعدادات Slack</h3>
        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>Webhook URL</label>
          <input type="url" placeholder="https://hooks.slack.com/..." style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }} />
        </div>
      </div>

      <div style={{ background: 'white', borderRadius: '8px', padding: '24px' }}>
        <h3 style={{ marginTop: 0 }}>إعدادات SMS</h3>
        <div style={{ display: 'grid', gap: '16px' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>Provider</label>
            <select style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}>
              <option value="twilio">Twilio</option>
              <option value="unifonic">Unifonic</option>
              <option value="yamamah">Yamamah</option>
            </select>
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>API Key</label>
            <input type="password" placeholder="API Key" style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }} />
          </div>
        </div>
      </div>

      <div style={{ marginTop: '16px', textAlign: 'left' }}>
        <button style={{
          padding: '12px 24px',
          background: '#3498db',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: 'pointer',
          fontSize: '16px',
        }}>
          حفظ الإعدادات
        </button>
      </div>
    </div>
  );

  if (loading) {
    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' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <h1 style={{ margin: 0, color: '#2c3e50' }}>🔔 إدارة التنبيهات</h1>
        <div style={{ display: 'flex', gap: '8px' }}>
          <span style={{ 
            padding: '8px 16px', 
            background: '#dc3545', 
            color: 'white', 
            borderRadius: '20px',
            fontSize: '14px',
          }}>
            {alerts.filter(a => a.status === 'active').length} نشط
          </span>
        </div>
      </div>

      <div style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', gap: '0', borderBottom: '2px solid #eee' }}>
          {[
            { key: 'alerts', label: 'التنبيهات', icon: '🔔' },
            { key: 'rules', label: 'القواعد', icon: '📋' },
            { key: 'settings', label: 'الإعدادات', icon: '⚙️' },
          ].map(tab => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key as any)}
              style={{
                padding: '12px 24px',
                background: activeTab === tab.key ? 'white' : 'transparent',
                border: 'none',
                borderBottom: activeTab === tab.key ? '2px solid #3498db' : '2px solid transparent',
                cursor: 'pointer',
                fontSize: '16px',
                color: activeTab === tab.key ? '#3498db' : '#666',
                marginBottom: '-2px',
              }}
            >
              {tab.icon} {tab.label}
            </button>
          ))}
        </div>
      </div>

      {activeTab === 'alerts' && renderAlerts()}
      {activeTab === 'rules' && renderRules()}
      {activeTab === 'settings' && renderSettings()}
    </div>
  );
};

export default AlertsManager;
