/**
 * Error Monitoring Dashboard
 * Real-time analytics and insights for system health
 */

const { useState, useEffect } = React;

// Monitoring Dashboard Component
function MonitoringDashboard({ token, user, onClose }) {
  const [activeTab, setActiveTab] = useState('overview');
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState({
    overview: null,
    errors: [],
    alerts: [],
    performance: [],
    statistics: [],
    trends: [],
  });
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState(30000); // 30 seconds

  // Fetch monitoring data
  const fetchData = async () => {
    try {
      setLoading(true);

      const headers = {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      };

      // Fetch all monitoring data in parallel
      const [overview, errors, alerts, performance, statistics, trends] = await Promise.all([
        fetch('/api/monitoring/health-overview', { headers }).then(r => r.json()),
        fetch('/api/monitoring/errors?limit=50', { headers }).then(r => r.json()),
        fetch('/api/monitoring/alerts', { headers }).then(r => r.json()),
        fetch('/api/monitoring/performance?limit=50', { headers }).then(r => r.json()),
        fetch('/api/monitoring/statistics?days=7', { headers }).then(r => r.json()),
        fetch('/api/monitoring/trends', { headers }).then(r => r.json()),
      ]);

      setData({
        overview,
        errors: errors.errors || [],
        alerts: alerts.alerts || [],
        performance: performance.performance_issues || [],
        statistics: statistics.statistics || [],
        trends: trends.trends || [],
      });
    } catch (error) {
      console.error('Failed to fetch monitoring data:', error);
    } finally {
      setLoading(false);
    }
  };

  // Initial fetch
  useEffect(() => {
    fetchData();
  }, []);

  // Auto-refresh
  useEffect(() => {
    if (!autoRefresh) return;

    const interval = setInterval(fetchData, refreshInterval);
    return () => clearInterval(interval);
  }, [autoRefresh, refreshInterval]);

  // Resolve error
  const resolveError = async (errorId, notes) => {
    try {
      const response = await fetch(`/api/monitoring/errors/${errorId}/resolve`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ notes }),
      });

      if (response.ok) {
        await fetchData();
        if (window.NotificationManager) {
          window.NotificationManager.success('Error resolved successfully');
        }
      }
    } catch (error) {
      console.error('Failed to resolve error:', error);
      if (window.NotificationManager) {
        window.NotificationManager.error('Failed to resolve error');
      }
    }
  };

  // Acknowledge alert
  const acknowledgeAlert = async (alertId) => {
    try {
      const response = await fetch(`/api/monitoring/alerts/${alertId}/acknowledge`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        await fetchData();
        if (window.NotificationManager) {
          window.NotificationManager.success('Alert acknowledged');
        }
      }
    } catch (error) {
      console.error('Failed to acknowledge alert:', error);
    }
  };

  // Calculate statistics
  const stats = {
    totalErrors: data.errors.length,
    criticalErrors: data.errors.filter(e => e.severity === 'critical').length,
    activeAlerts: data.alerts.filter(a => a.status === 'triggered').length,
    slowOperations: data.performance.length,
  };

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-gray-800 rounded-xl shadow-2xl w-full max-w-7xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="bg-gradient-to-r from-blue-600 to-purple-600 p-6 flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-white flex items-center">
              <i className="fas fa-chart-line mr-3"></i>
              Error Monitoring Dashboard
            </h2>
            <p className="text-blue-100 text-sm mt-1">
              Real-time system health and error analytics
            </p>
          </div>
          <div className="flex items-center gap-3">
            {/* Auto-refresh toggle */}
            <label className="flex items-center gap-2 text-white text-sm cursor-pointer">
              <input
                type="checkbox"
                checked={autoRefresh}
                onChange={(e) => setAutoRefresh(e.target.checked)}
                className="rounded"
              />
              <i className="fas fa-sync-alt"></i>
              Auto-refresh
            </label>
            
            {/* Refresh button */}
            <button
              onClick={fetchData}
              disabled={loading}
              className="bg-white/20 hover:bg-white/30 text-white px-4 py-2 rounded-lg transition-colors disabled:opacity-50"
            >
              <i className={`fas fa-sync-alt mr-2 ${loading ? 'animate-spin' : ''}`}></i>
              Refresh
            </button>

            {/* Close button */}
            <button
              onClick={onClose}
              className="bg-white/20 hover:bg-white/30 text-white p-2 rounded-lg transition-colors"
            >
              <i className="fas fa-times"></i>
            </button>
          </div>
        </div>

        {/* Stats Overview */}
        <div className="p-6 bg-gray-900 border-b border-gray-700">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <StatCard
              icon="exclamation-circle"
              label="Total Errors"
              value={stats.totalErrors}
              color="blue"
            />
            <StatCard
              icon="exclamation-triangle"
              label="Critical Errors"
              value={stats.criticalErrors}
              color="red"
            />
            <StatCard
              icon="bell"
              label="Active Alerts"
              value={stats.activeAlerts}
              color="yellow"
            />
            <StatCard
              icon="clock"
              label="Slow Operations"
              value={stats.slowOperations}
              color="purple"
            />
          </div>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-gray-700 bg-gray-900">
          <Tab
            active={activeTab === 'overview'}
            onClick={() => setActiveTab('overview')}
            icon="chart-pie"
            label="Overview"
          />
          <Tab
            active={activeTab === 'errors'}
            onClick={() => setActiveTab('errors')}
            icon="bug"
            label="Errors"
            badge={stats.totalErrors}
          />
          <Tab
            active={activeTab === 'alerts'}
            onClick={() => setActiveTab('alerts')}
            icon="bell"
            label="Alerts"
            badge={stats.activeAlerts}
          />
          <Tab
            active={activeTab === 'performance'}
            onClick={() => setActiveTab('performance')}
            icon="tachometer-alt"
            label="Performance"
          />
          <Tab
            active={activeTab === 'trends'}
            onClick={() => setActiveTab('trends')}
            icon="chart-line"
            label="Trends"
          />
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading && activeTab !== 'overview' ? (
            <LoadingSpinner />
          ) : (
            <>
              {activeTab === 'overview' && (
                <OverviewTab data={data.overview} trends={data.trends} />
              )}
              {activeTab === 'errors' && (
                <ErrorsTab errors={data.errors} onResolve={resolveError} />
              )}
              {activeTab === 'alerts' && (
                <AlertsTab alerts={data.alerts} onAcknowledge={acknowledgeAlert} />
              )}
              {activeTab === 'performance' && (
                <PerformanceTab performance={data.performance} />
              )}
              {activeTab === 'trends' && (
                <TrendsTab trends={data.trends} statistics={data.statistics} />
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// Stat Card Component
function StatCard({ icon, label, value, color }) {
  const colorClasses = {
    blue: 'from-blue-500 to-blue-600',
    red: 'from-red-500 to-red-600',
    yellow: 'from-yellow-500 to-yellow-600',
    purple: 'from-purple-500 to-purple-600',
  };

  return (
    <div className={`bg-gradient-to-br ${colorClasses[color]} rounded-lg p-4 text-white`}>
      <div className="flex items-center justify-between mb-2">
        <i className={`fas fa-${icon} text-2xl opacity-80`}></i>
        <span className="text-3xl font-bold">{value}</span>
      </div>
      <div className="text-sm opacity-90">{label}</div>
    </div>
  );
}

// Tab Component
function Tab({ active, onClick, icon, label, badge }) {
  return (
    <button
      onClick={onClick}
      className={`px-6 py-3 font-medium transition-colors relative ${
        active
          ? 'text-blue-400 border-b-2 border-blue-400'
          : 'text-gray-400 hover:text-gray-200'
      }`}
    >
      <i className={`fas fa-${icon} mr-2`}></i>
      {label}
      {badge > 0 && (
        <span className="ml-2 bg-red-500 text-white text-xs px-2 py-1 rounded-full">
          {badge}
        </span>
      )}
    </button>
  );
}

// Overview Tab
function OverviewTab({ data, trends }) {
  if (!data) return <div className="text-gray-400">No data available</div>;

  const errorsByCategory = data.errors?.reduce((acc, err) => {
    acc[err.severity] = (acc[err.severity] || 0) + err.count;
    return acc;
  }, {}) || {};

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Error Distribution */}
        <div className="bg-gray-900 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
            <i className="fas fa-chart-pie mr-2 text-blue-400"></i>
            Error Distribution (Last Hour)
          </h3>
          <div className="space-y-3">
            {Object.entries(errorsByCategory).map(([severity, count]) => (
              <div key={severity} className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className={`w-3 h-3 rounded-full ${getSeverityColor(severity)}`}></span>
                  <span className="text-gray-300 capitalize">{severity}</span>
                </div>
                <span className="text-white font-semibold">{count}</span>
              </div>
            ))}
          </div>
        </div>

        {/* System Health */}
        <div className="bg-gray-900 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
            <i className="fas fa-heartbeat mr-2 text-green-400"></i>
            System Health
          </h3>
          <div className="space-y-3">
            {data.health?.slice(0, 5).map((health, idx) => (
              <div key={idx} className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className={`w-3 h-3 rounded-full ${getHealthColor(health.status)}`}></span>
                  <span className="text-gray-300">{health.component}</span>
                </div>
                <span className="text-gray-400 text-sm">{health.response_time_ms}ms</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Quick Stats */}
      <div className="bg-gray-900 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
          <i className="fas fa-info-circle mr-2 text-purple-400"></i>
          Quick Statistics
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <QuickStat label="Uptime" value="99.8%" icon="check-circle" color="green" />
          <QuickStat label="Avg Response Time" value="~230ms" icon="clock" color="blue" />
          <QuickStat label="Active Users" value="24" icon="users" color="purple" />
          <QuickStat label="API Calls" value="1,234" icon="exchange-alt" color="yellow" />
        </div>
      </div>
    </div>
  );
}

// Quick Stat Component
function QuickStat({ label, value, icon, color }) {
  const colorClasses = {
    green: 'text-green-400',
    blue: 'text-blue-400',
    purple: 'text-purple-400',
    yellow: 'text-yellow-400',
  };

  return (
    <div className="text-center">
      <i className={`fas fa-${icon} ${colorClasses[color]} text-2xl mb-2`}></i>
      <div className="text-2xl font-bold text-white">{value}</div>
      <div className="text-sm text-gray-400">{label}</div>
    </div>
  );
}

// Errors Tab
function ErrorsTab({ errors, onResolve }) {
  const [selectedError, setSelectedError] = useState(null);
  const [filter, setFilter] = useState('all');

  const filteredErrors = filter === 'all' 
    ? errors 
    : errors.filter(e => e.severity === filter);

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex gap-2">
        {['all', 'critical', 'error', 'warning'].map(f => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              filter === f
                ? 'bg-blue-600 text-white'
                : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
            }`}
          >
            {f.charAt(0).toUpperCase() + f.slice(1)}
          </button>
        ))}
      </div>

      {/* Error List */}
      <div className="space-y-2">
        {filteredErrors.length === 0 ? (
          <div className="text-center text-gray-400 py-12">
            <i className="fas fa-check-circle text-5xl mb-4 text-green-500"></i>
            <p className="text-lg">No errors found!</p>
          </div>
        ) : (
          filteredErrors.map(error => (
            <ErrorCard
              key={error.id}
              error={error}
              onViewDetails={() => setSelectedError(error)}
              onResolve={onResolve}
            />
          ))
        )}
      </div>

      {/* Error Details Modal */}
      {selectedError && (
        <ErrorDetailsModal
          error={selectedError}
          onClose={() => setSelectedError(null)}
          onResolve={onResolve}
        />
      )}
    </div>
  );
}

// Error Card Component
function ErrorCard({ error, onViewDetails, onResolve }) {
  const severityColors = {
    critical: 'border-red-500 bg-red-500/10',
    error: 'border-orange-500 bg-orange-500/10',
    warning: 'border-yellow-500 bg-yellow-500/10',
    info: 'border-blue-500 bg-blue-500/10',
  };

  return (
    <div className={`border-l-4 ${severityColors[error.severity]} bg-gray-900 rounded-lg p-4`}>
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className={`px-2 py-1 rounded text-xs font-semibold ${getSeverityBadge(error.severity)}`}>
              {error.severity.toUpperCase()}
            </span>
            <span className="px-2 py-1 bg-gray-700 rounded text-xs text-gray-300">
              {error.category}
            </span>
            <span className="text-xs text-gray-400">
              {new Date(error.timestamp).toLocaleString()}
            </span>
          </div>
          <div className="text-white font-medium mb-1">{error.message}</div>
          {error.request_path && (
            <div className="text-sm text-gray-400">
              <i className="fas fa-link mr-1"></i>
              {error.request_method} {error.request_path}
            </div>
          )}
          {error.user_email && (
            <div className="text-sm text-gray-400">
              <i className="fas fa-user mr-1"></i>
              {error.user_email}
            </div>
          )}
        </div>
        <div className="flex gap-2">
          <button
            onClick={onViewDetails}
            className="text-blue-400 hover:text-blue-300 text-sm"
          >
            <i className="fas fa-eye mr-1"></i>
            Details
          </button>
          {!error.resolved && (
            <button
              onClick={() => onResolve(error.id, 'Resolved from dashboard')}
              className="text-green-400 hover:text-green-300 text-sm"
            >
              <i className="fas fa-check mr-1"></i>
              Resolve
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// Error Details Modal
function ErrorDetailsModal({ error, onClose, onResolve }) {
  return (
    <div className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4">
      <div className="bg-gray-800 rounded-lg max-w-4xl w-full max-h-[80vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex items-start justify-between mb-4">
            <h3 className="text-xl font-bold text-white">Error Details</h3>
            <button onClick={onClose} className="text-gray-400 hover:text-white">
              <i className="fas fa-times"></i>
            </button>
          </div>

          <div className="space-y-4">
            {/* Basic Info */}
            <div className="grid grid-cols-2 gap-4">
              <InfoField label="Severity" value={error.severity} />
              <InfoField label="Category" value={error.category} />
              <InfoField label="Timestamp" value={new Date(error.timestamp).toLocaleString()} />
              <InfoField label="Request ID" value={error.request_id} />
            </div>

            {/* Message */}
            <div>
              <div className="text-sm text-gray-400 mb-1">Message:</div>
              <div className="bg-gray-900 p-3 rounded text-white">{error.message}</div>
            </div>

            {/* Stack Trace */}
            {error.stack_trace && (
              <div>
                <div className="text-sm text-gray-400 mb-1">Stack Trace:</div>
                <pre className="bg-black p-3 rounded text-red-400 text-xs overflow-auto max-h-60">
                  {error.stack_trace}
                </pre>
              </div>
            )}

            {/* User Context */}
            {(error.user_email || error.user_id) && (
              <div className="grid grid-cols-2 gap-4">
                {error.user_email && <InfoField label="User Email" value={error.user_email} />}
                {error.user_id && <InfoField label="User ID" value={error.user_id} />}
              </div>
            )}

            {/* Actions */}
            <div className="flex gap-3 pt-4 border-t border-gray-700">
              {!error.resolved && (
                <button
                  onClick={() => {
                    onResolve(error.id, 'Resolved from details view');
                    onClose();
                  }}
                  className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg"
                >
                  <i className="fas fa-check mr-2"></i>
                  Mark as Resolved
                </button>
              )}
              <button
                onClick={onClose}
                className="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded-lg"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Info Field Component
function InfoField({ label, value }) {
  return (
    <div>
      <div className="text-sm text-gray-400 mb-1">{label}:</div>
      <div className="bg-gray-900 p-2 rounded text-white text-sm">{value || 'N/A'}</div>
    </div>
  );
}

// Alerts Tab
function AlertsTab({ alerts, onAcknowledge }) {
  return (
    <div className="space-y-4">
      {alerts.length === 0 ? (
        <div className="text-center text-gray-400 py-12">
          <i className="fas fa-bell-slash text-5xl mb-4"></i>
          <p className="text-lg">No active alerts</p>
        </div>
      ) : (
        alerts.map(alert => (
          <AlertCard key={alert.id} alert={alert} onAcknowledge={onAcknowledge} />
        ))
      )}
    </div>
  );
}

// Alert Card Component
function AlertCard({ alert, onAcknowledge }) {
  const severityColors = {
    critical: 'border-red-500 bg-red-500/10',
    high: 'border-orange-500 bg-orange-500/10',
    medium: 'border-yellow-500 bg-yellow-500/10',
    low: 'border-blue-500 bg-blue-500/10',
  };

  return (
    <div className={`border-l-4 ${severityColors[alert.severity]} bg-gray-900 rounded-lg p-4`}>
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className={`px-2 py-1 rounded text-xs font-semibold ${getSeverityBadge(alert.severity)}`}>
              {alert.severity.toUpperCase()}
            </span>
            <span className="px-2 py-1 bg-gray-700 rounded text-xs text-gray-300">
              {alert.alert_type}
            </span>
            <span className="text-xs text-gray-400">
              {new Date(alert.timestamp).toLocaleString()}
            </span>
          </div>
          <div className="text-white font-medium mb-1">{alert.title}</div>
          <div className="text-gray-300 text-sm">{alert.message}</div>
        </div>
        {alert.status === 'triggered' && (
          <button
            onClick={() => onAcknowledge(alert.id)}
            className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm"
          >
            <i className="fas fa-check mr-1"></i>
            Acknowledge
          </button>
        )}
      </div>
    </div>
  );
}

// Performance Tab
function PerformanceTab({ performance }) {
  return (
    <div className="space-y-4">
      {performance.length === 0 ? (
        <div className="text-center text-gray-400 py-12">
          <i className="fas fa-rocket text-5xl mb-4 text-green-500"></i>
          <p className="text-lg">Great! No performance issues detected</p>
        </div>
      ) : (
        performance.map(perf => (
          <PerformanceCard key={perf.id} perf={perf} />
        ))
      )}
    </div>
  );
}

// Performance Card Component
function PerformanceCard({ perf }) {
  return (
    <div className="bg-gray-900 rounded-lg p-4 border border-yellow-500/30">
      <div className="flex items-start justify-between mb-2">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className="px-2 py-1 bg-yellow-500/20 text-yellow-400 rounded text-xs font-semibold">
              {perf.metric_type}
            </span>
            <span className="text-xs text-gray-400">
              {new Date(perf.timestamp).toLocaleString()}
            </span>
          </div>
          <div className="text-white font-medium mb-1">{perf.operation_name}</div>
        </div>
      </div>
      <div className="grid grid-cols-3 gap-4 mt-3">
        <div>
          <div className="text-xs text-gray-400">Duration</div>
          <div className="text-lg font-semibold text-orange-400">{perf.duration_ms}ms</div>
        </div>
        <div>
          <div className="text-xs text-gray-400">Threshold</div>
          <div className="text-lg font-semibold text-gray-300">{perf.threshold_ms}ms</div>
        </div>
        <div>
          <div className="text-xs text-gray-400">Exceeded By</div>
          <div className="text-lg font-semibold text-red-400">+{perf.exceeded_by_ms}ms</div>
        </div>
      </div>
    </div>
  );
}

// Trends Tab
function TrendsTab({ trends, statistics }) {
  return (
    <div className="space-y-6">
      <div className="bg-gray-900 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
          <i className="fas fa-chart-line mr-2 text-blue-400"></i>
          Error Trends (Last 7 Days)
        </h3>
        {trends.length === 0 ? (
          <div className="text-gray-400 text-center py-8">No trend data available</div>
        ) : (
          <div className="space-y-2">
            {trends.map((trend, idx) => (
              <div key={idx} className="flex items-center justify-between p-3 bg-gray-800 rounded">
                <span className="text-gray-300">{trend.date}</span>
                <div className="flex gap-4 text-sm">
                  <span className="text-red-400">Critical: {trend.critical_count}</span>
                  <span className="text-orange-400">Errors: {trend.error_count}</span>
                  <span className="text-yellow-400">Warnings: {trend.warning_count}</span>
                  <span className="text-gray-400">Avg Response: {trend.avg_response_time_ms}ms</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// Helper Functions
function getSeverityColor(severity) {
  const colors = {
    critical: 'bg-red-500',
    error: 'bg-orange-500',
    warning: 'bg-yellow-500',
    info: 'bg-blue-500',
  };
  return colors[severity] || 'bg-gray-500';
}

function getSeverityBadge(severity) {
  const badges = {
    critical: 'bg-red-500/20 text-red-400',
    high: 'bg-orange-500/20 text-orange-400',
    error: 'bg-orange-500/20 text-orange-400',
    medium: 'bg-yellow-500/20 text-yellow-400',
    warning: 'bg-yellow-500/20 text-yellow-400',
    low: 'bg-blue-500/20 text-blue-400',
    info: 'bg-blue-500/20 text-blue-400',
  };
  return badges[severity] || 'bg-gray-500/20 text-gray-400';
}

function getHealthColor(status) {
  const colors = {
    healthy: 'bg-green-500',
    degraded: 'bg-yellow-500',
    down: 'bg-red-500',
  };
  return colors[status] || 'bg-gray-500';
}

// Loading Spinner
function LoadingSpinner() {
  return (
    <div className="flex items-center justify-center py-12">
      <div className="animate-spin text-blue-400 text-4xl">
        <i className="fas fa-circle-notch"></i>
      </div>
    </div>
  );
}

// Export for use in app
window.MonitoringDashboard = MonitoringDashboard;
