/**
 * ReportsBuilder Component - منشئ التقارير
 */

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

interface ReportDefinition {
  id: string;
  name: string;
  nameAr: string;
  frequency: 'daily' | 'weekly' | 'monthly' | 'on_demand';
  schedule?: string;
  recipients: string[];
  formats: string[];
  isActive: boolean;
}

interface GeneratedReport {
  id: string;
  name: string;
  frequency: string;
  status: 'pending' | 'generating' | 'completed' | 'failed';
  generatedAt: string;
  completedAt?: string;
}

export const ReportsBuilder: React.FC = () => {
  const [definitions, setDefinitions] = useState<ReportDefinition[]>([]);
  const [reports, setReports] = useState<GeneratedReport[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'reports' | 'definitions' | 'create'>('reports');
  const [generating, setGenerating] = useState<string | null>(null);

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [defsRes, reportsRes] = await Promise.all([
        fetch('/api/plugins/database-connector/reports/definitions'),
        fetch('/api/plugins/database-connector/reports'),
      ]);

      if (defsRes.ok) setDefinitions(await defsRes.json());
      if (reportsRes.ok) setReports(await reportsRes.json());
    } catch (error) {
      console.error('Error loading data:', error);
      // Mock data
      setDefinitions([
        { id: 'DAILY_PERFORMANCE', name: 'Daily Performance', nameAr: 'تقرير الأداء اليومي', frequency: 'daily', schedule: '0 18 * * *', recipients: ['manager@example.com'], formats: ['pdf', 'html'], isActive: true },
        { id: 'WEEKLY_PERFORMANCE', name: 'Weekly Performance', nameAr: 'تقرير الأداء الأسبوعي', frequency: 'weekly', schedule: '0 9 * * 0', recipients: ['manager@example.com'], formats: ['pdf', 'excel'], isActive: true },
        { id: 'HIGH_RISK_REPORT', name: 'High Risk Report', nameAr: 'تقرير العملاء عالي المخاطر', frequency: 'daily', schedule: '0 8 * * *', recipients: ['supervisor@example.com'], formats: ['pdf'], isActive: true },
      ]);
      setReports([
        { id: 'R1', name: 'تقرير الأداء اليومي', frequency: 'daily', status: 'completed', generatedAt: '2026-01-30T18:00:00Z', completedAt: '2026-01-30T18:01:30Z' },
        { id: 'R2', name: 'تقرير العملاء عالي المخاطر', frequency: 'daily', status: 'completed', generatedAt: '2026-01-30T08:00:00Z', completedAt: '2026-01-30T08:00:45Z' },
      ]);
    }
    setLoading(false);
  };

  const generateReport = async (definitionId: string) => {
    setGenerating(definitionId);
    try {
      await fetch(`/api/plugins/database-connector/reports/generate/${definitionId}`, {
        method: 'POST',
      });
      await loadData();
    } catch (error) {
      console.error('Error generating report:', error);
    }
    setGenerating(null);
  };

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

  const getFrequencyLabel = (freq: string) => {
    switch (freq) {
      case 'daily': return 'يومي';
      case 'weekly': return 'أسبوعي';
      case 'monthly': return 'شهري';
      case 'on_demand': return 'عند الطلب';
      default: return freq;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return '#28a745';
      case 'generating': return '#ffc107';
      case 'failed': return '#dc3545';
      default: return '#6c757d';
    }
  };

  const renderReports = () => (
    <div>
      <div style={{ marginBottom: '16px' }}>
        <button 
          onClick={loadData}
          style={{ padding: '8px 16px', background: '#3498db', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}
        >
          تحديث
        </button>
      </div>

      <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: 'center' }}>الإجراءات</th>
          </tr>
        </thead>
        <tbody>
          {reports.length === 0 ? (
            <tr>
              <td colSpan={5} style={{ padding: '40px', textAlign: 'center', color: '#666' }}>
                لا توجد تقارير
              </td>
            </tr>
          ) : (
            reports.map(report => (
              <tr key={report.id} style={{ borderBottom: '1px solid #eee' }}>
                <td style={{ padding: '12px' }}>{report.name}</td>
                <td style={{ padding: '12px' }}>{getFrequencyLabel(report.frequency)}</td>
                <td style={{ padding: '12px' }}>
                  <span style={{
                    padding: '4px 12px',
                    borderRadius: '12px',
                    background: getStatusColor(report.status),
                    color: 'white',
                    fontSize: '12px',
                  }}>
                    {report.status === 'completed' ? 'مكتمل' : report.status === 'generating' ? 'قيد الإنشاء' : 'فشل'}
                  </span>
                </td>
                <td style={{ padding: '12px' }}>{new Date(report.generatedAt).toLocaleString('ar-SA')}</td>
                <td style={{ padding: '12px', textAlign: 'center' }}>
                  <button style={{ padding: '6px 12px', marginLeft: '8px', background: '#3498db', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>
                    عرض
                  </button>
                  <button style={{ padding: '6px 12px', background: '#28a745', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>
                    تحميل
                  </button>
                </td>
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );

  const renderDefinitions = () => (
    <div>
      <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>
            <th style={{ padding: '12px', textAlign: 'center' }}>إجراء</th>
          </tr>
        </thead>
        <tbody>
          {definitions.map(def => (
            <tr key={def.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: '12px' }}>
                <div style={{ fontWeight: 'bold' }}>{def.nameAr}</div>
                <div style={{ fontSize: '12px', color: '#666' }}>{def.name}</div>
              </td>
              <td style={{ padding: '12px' }}>{getFrequencyLabel(def.frequency)}</td>
              <td style={{ padding: '12px', fontSize: '12px', color: '#666' }}>{def.schedule || '-'}</td>
              <td style={{ padding: '12px', fontSize: '12px' }}>{def.recipients.length} مستلم</td>
              <td style={{ padding: '12px', fontSize: '12px' }}>{def.formats.join(', ').toUpperCase()}</td>
              <td style={{ padding: '12px', textAlign: 'center' }}>
                <label style={{ cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={def.isActive}
                    onChange={(e) => toggleDefinition(def.id, e.target.checked)}
                    style={{ width: '18px', height: '18px' }}
                  />
                </label>
              </td>
              <td style={{ padding: '12px', textAlign: 'center' }}>
                <button 
                  onClick={() => generateReport(def.id)}
                  disabled={generating === def.id}
                  style={{ 
                    padding: '6px 12px', 
                    background: generating === def.id ? '#ccc' : '#3498db', 
                    color: 'white', 
                    border: 'none', 
                    borderRadius: '4px', 
                    cursor: generating === def.id ? 'not-allowed' : 'pointer' 
                  }}
                >
                  {generating === def.id ? 'جاري...' : 'إنشاء الآن'}
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  const renderCreate = () => (
    <div style={{ background: 'white', borderRadius: '8px', padding: '24px' }}>
      <h3 style={{ marginTop: 0 }}>إنشاء تقرير جديد</h3>
      
      <div style={{ display: 'grid', gap: '16px' }}>
        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>اسم التقرير</label>
          <input type="text" placeholder="اسم التقرير" style={{ width: '100%', padding: '10px', 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' }}>التكرار</label>
            <select style={{ width: '100%', padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }}>
              <option value="daily">يومي</option>
              <option value="weekly">أسبوعي</option>
              <option value="monthly">شهري</option>
              <option value="on_demand">عند الطلب</option>
            </select>
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>الوقت</label>
            <input type="time" style={{ width: '100%', padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }} />
          </div>
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>الأقسام</label>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px' }}>
            {['ملخص المكالمات', 'التحصيل', 'أداء الوكلاء', 'العملاء عالي المخاطر', 'المتابعات', 'التوصيات'].map(section => (
              <label key={section} style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
                <input type="checkbox" />
                {section}
              </label>
            ))}
          </div>
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>المستلمين</label>
          <input type="text" placeholder="email@example.com, email2@example.com" style={{ width: '100%', padding: '10px', borderRadius: '4px', border: '1px solid #ddd' }} />
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>الصيغ</label>
          <div style={{ display: 'flex', gap: '16px' }}>
            {['PDF', 'Excel', 'HTML'].map(format => (
              <label key={format} style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
                <input type="checkbox" />
                {format}
              </label>
            ))}
          </div>
        </div>

        <div style={{ marginTop: '16px' }}>
          <button style={{
            padding: '12px 24px',
            background: '#3498db',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '16px',
          }}>
            إنشاء التقرير
          </button>
        </div>
      </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' }}>
      <h1 style={{ margin: '0 0 24px 0', color: '#2c3e50' }}>📊 منشئ التقارير</h1>

      <div style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', gap: '0', borderBottom: '2px solid #eee' }}>
          {[
            { key: 'reports', label: 'التقارير المنشأة', icon: '📄' },
            { key: 'definitions', label: 'قوالب التقارير', icon: '📋' },
            { key: 'create', 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 === 'reports' && renderReports()}
      {activeTab === 'definitions' && renderDefinitions()}
      {activeTab === 'create' && renderCreate()}
    </div>
  );
};

export default ReportsBuilder;
