import React, { useState, useEffect } from 'react';
import { 
  Activity, 
  AlertTriangle, 
  CheckCircle, 
  Clock, 
  TrendingUp, 
  RefreshCw,
  AlertCircle
} from 'lucide-react';

interface UploadMetrics {
  totalUploads: number;
  successfulUploads: number;
  failedUploads: number;
  successRate: number;
  averageProcessingTime: number;
  totalProcessingTime: number;
  uploadsByHour: { [hour: string]: number };
  errorsByType: { [errorType: string]: number };
  errorsByStage: { [stage: string]: number };
  fileSizeDistribution: {
    small: number;
    medium: number;
    large: number;
  };
  processingTimeDistribution: {
    fast: number;
    normal: number;
    slow: number;
  };
}

interface UploadHealthStatus {
  status: 'healthy' | 'degraded' | 'unhealthy';
  successRate: number;
  averageProcessingTime: number;
  recentErrors: Array<{
    id: string;
    userId: string;
    fileInfo: {
      originalName: string;
      size: number;
      mimetype: string;
    };
    status: string;
    stage?: string;
    error?: {
      message: string;
      code?: string;
      type: string;
    };
    processingTime?: number;
    timestamp: string;
    correlationId?: string;
  }>;
  recommendations: string[];
  timestamp: string;
}

interface RealTimeStats {
  activeUploads: number;
  uploadsLastMinute: number;
  uploadsLastHour: number;
  currentSuccessRate: number;
}

interface ErrorAnalysis {
  topErrorTypes: Array<{ type: string; count: number; percentage: number }>;
  topErrorStages: Array<{ stage: string; count: number; percentage: number }>;
  errorTrends: Array<{ hour: string; errorCount: number; totalCount: number }>;
}

interface DashboardData {
  metrics: UploadMetrics;
  healthStatus: UploadHealthStatus;
  realTimeStats: RealTimeStats;
  errorAnalysis: ErrorAnalysis;
  timestamp: string;
}

const UploadMonitoringDashboard: React.FC = () => {
  const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [timeRange, setTimeRange] = useState('24');
  const [autoRefresh, setAutoRefresh] = useState(true);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/monitoring/dashboard?hours=${timeRange}`);
      if (!response.ok) {
        throw new Error('Failed to fetch dashboard data');
      }
      const result = await response.json();
      setDashboardData(result.data);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch data');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDashboardData();
  }, [timeRange]);

  useEffect(() => {
    if (!autoRefresh) return;

    const interval = setInterval(fetchDashboardData, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, [autoRefresh, timeRange]);

  const getHealthStatusColor = (status: string) => {
    switch (status) {
      case 'healthy':
        return 'bg-green-500';
      case 'degraded':
        return 'bg-yellow-500';
      case 'unhealthy':
        return 'bg-red-500';
      default:
        return 'bg-gray-500';
    }
  };

  const getHealthStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy':
        return <CheckCircle className="h-5 w-5 text-green-500" />;
      case 'degraded':
        return <AlertTriangle className="h-5 w-5 text-yellow-500" />;
      case 'unhealthy':
        return <AlertCircle className="h-5 w-5 text-red-500" />;
      default:
        return <Activity className="h-5 w-5 text-gray-500" />;
    }
  };

  const formatTime = (ms: number) => {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}m`;
  };



  if (loading && !dashboardData) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw className="h-8 w-8 animate-spin" />
        <span className="ml-2">Loading dashboard data...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
        <div className="flex items-center">
          <AlertCircle className="h-4 w-4 text-red-600 mr-2" />
          <span className="text-red-800">{error}</span>
        </div>
      </div>
    );
  }

  if (!dashboardData) {
    return (
      <div className="mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
        <div className="flex items-center">
          <AlertCircle className="h-4 w-4 text-yellow-600 mr-2" />
          <span className="text-yellow-800">No dashboard data available</span>
        </div>
      </div>
    );
  }

  const { metrics, healthStatus, realTimeStats, errorAnalysis } = dashboardData;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Upload Pipeline Monitoring</h1>
          <p className="text-muted-foreground">
            Real-time monitoring and analytics for document upload processing
          </p>
        </div>
        <div className="flex items-center space-x-4">
          <select 
            value={timeRange} 
            onChange={(e) => setTimeRange(e.target.value)}
            className="w-32 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="1">1 Hour</option>
            <option value="6">6 Hours</option>
            <option value="24">24 Hours</option>
            <option value="168">7 Days</option>
          </select>
          <button
            className={`px-4 py-2 text-sm font-medium rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 ${
              autoRefresh 
                ? 'bg-blue-600 text-white hover:bg-blue-700' 
                : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
            }`}
            onClick={() => setAutoRefresh(!autoRefresh)}
          >
            <RefreshCw className={`h-4 w-4 mr-2 inline ${autoRefresh ? 'animate-spin' : ''}`} />
            Auto Refresh
          </button>
          <button 
            className="px-4 py-2 text-sm font-medium bg-white text-gray-700 border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
            onClick={fetchDashboardData}
          >
            <RefreshCw className="h-4 w-4 mr-2 inline" />
            Refresh
          </button>
        </div>
      </div>

      {/* Health Status */}
      <div className="bg-white shadow rounded-lg border border-gray-200">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900 flex items-center space-x-2">
            {getHealthStatusIcon(healthStatus.status)}
            <span>System Health Status</span>
            <span className={`ml-2 px-2 py-1 text-xs font-medium rounded-full ${getHealthStatusColor(healthStatus.status)} text-white`}>
              {healthStatus.status.toUpperCase()}
            </span>
          </h3>
        </div>
        <div className="px-6 py-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="text-center">
              <div className="text-2xl font-bold text-green-600">
                {(healthStatus.successRate * 100).toFixed(1)}%
              </div>
              <div className="text-sm text-muted-foreground">Success Rate</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-blue-600">
                {formatTime(healthStatus.averageProcessingTime)}
              </div>
              <div className="text-sm text-muted-foreground">Avg Processing Time</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-orange-600">
                {healthStatus.recentErrors.length}
              </div>
              <div className="text-sm text-muted-foreground">Recent Errors</div>
            </div>
          </div>
          
          {healthStatus.recommendations.length > 0 && (
            <div className="mt-4">
              <h4 className="font-semibold mb-2">Recommendations:</h4>
              <ul className="space-y-1">
                {healthStatus.recommendations.map((rec, index) => (
                  <li key={index} className="text-sm text-muted-foreground flex items-start">
                    <AlertCircle className="h-4 w-4 mr-2 mt-0.5 text-yellow-500" />
                    {rec}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      </div>

      {/* Real-time Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white shadow rounded-lg border border-gray-200 p-4">
          <div className="flex items-center space-x-2">
            <Activity className="h-4 w-4 text-blue-500" />
            <span className="text-sm font-medium">Active Uploads</span>
          </div>
          <div className="text-2xl font-bold">{realTimeStats.activeUploads}</div>
        </div>
        
        <div className="bg-white shadow rounded-lg border border-gray-200 p-4">
          <div className="flex items-center space-x-2">
            <Clock className="h-4 w-4 text-green-500" />
            <span className="text-sm font-medium">Last Minute</span>
          </div>
          <div className="text-2xl font-bold">{realTimeStats.uploadsLastMinute}</div>
        </div>
        
        <div className="bg-white shadow rounded-lg border border-gray-200 p-4">
          <div className="flex items-center space-x-2">
            <TrendingUp className="h-4 w-4 text-purple-500" />
            <span className="text-sm font-medium">Last Hour</span>
          </div>
          <div className="text-2xl font-bold">{realTimeStats.uploadsLastHour}</div>
        </div>
        
        <div className="bg-white shadow rounded-lg border border-gray-200 p-4">
          <div className="flex items-center space-x-2">
            <CheckCircle className="h-4 w-4 text-green-500" />
            <span className="text-sm font-medium">Success Rate</span>
          </div>
          <div className="text-2xl font-bold">
            {(realTimeStats.currentSuccessRate * 100).toFixed(1)}%
          </div>
        </div>
      </div>

      {/* Detailed Metrics */}
      <div className="space-y-4">
        <div className="border-b border-gray-200">
          <nav className="-mb-px flex space-x-8">
            <button className="border-b-2 border-blue-500 py-2 px-1 text-sm font-medium text-blue-600">
              Overview
            </button>
            <button className="border-b-2 border-transparent py-2 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300">
              Error Analysis
            </button>
            <button className="border-b-2 border-transparent py-2 px-1 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300">
              Performance
            </button>
          </nav>
        </div>

        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">Upload Statistics</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-4">
                                      <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span>Success Rate</span>
                        <span>{(metrics.successRate * 100).toFixed(1)}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className="bg-blue-600 h-2 rounded-full" 
                          style={{ width: `${metrics.successRate * 100}%` }}
                        ></div>
                      </div>
                    </div>
                  
                  <div className="grid grid-cols-2 gap-4 text-center">
                    <div>
                      <div className="text-2xl font-bold text-green-600">
                        {metrics.successfulUploads}
                      </div>
                      <div className="text-sm text-muted-foreground">Successful</div>
                    </div>
                    <div>
                      <div className="text-2xl font-bold text-red-600">
                        {metrics.failedUploads}
                      </div>
                      <div className="text-sm text-muted-foreground">Failed</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">File Size Distribution</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-3">
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Small (&lt; 1MB)</span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-full">{metrics.fileSizeDistribution.small}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Medium (1MB - 10MB)</span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-full">{metrics.fileSizeDistribution.medium}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Large (&gt; 10MB)</span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-full">{metrics.fileSizeDistribution.large}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">Top Error Types</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-3">
                  {errorAnalysis.topErrorTypes.map((error, index) => (
                    <div key={index} className="flex justify-between items-center">
                      <span className="text-sm truncate">{error.type}</span>
                      <div className="flex items-center space-x-2">
                        <span className="text-sm font-medium">{error.count}</span>
                        <span className="text-xs text-muted-foreground">
                          ({error.percentage.toFixed(1)}%)
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">Top Error Stages</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-3">
                  {errorAnalysis.topErrorStages.map((stage, index) => (
                    <div key={index} className="flex justify-between items-center">
                      <span className="text-sm truncate">{stage.stage}</span>
                      <div className="flex items-center space-x-2">
                        <span className="text-sm font-medium">{stage.count}</span>
                        <span className="text-xs text-muted-foreground">
                          ({stage.percentage.toFixed(1)}%)
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {healthStatus.recentErrors.length > 0 && (
            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">Recent Errors</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-3">
                  {healthStatus.recentErrors.slice(0, 5).map((error) => (
                    <div key={error.id} className="border rounded-lg p-3">
                      <div className="flex justify-between items-start mb-2">
                        <span className="font-medium text-sm">{error.fileInfo.originalName}</span>
                        <span className="text-xs text-muted-foreground">
                          {new Date(error.timestamp).toLocaleString()}
                        </span>
                      </div>
                      <div className="text-sm text-muted-foreground mb-1">
                        Stage: {error.stage || 'Unknown'}
                      </div>
                      {error.error && (
                        <div className="text-sm text-red-600">
                          {error.error.message}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">Processing Time Distribution</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-3">
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Fast (&lt; 30s)</span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-green-600 rounded-full">
                      {metrics.processingTimeDistribution.fast}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Normal (30s - 5m)</span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-blue-600 rounded-full">
                      {metrics.processingTimeDistribution.normal}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">Slow (&gt; 5m)</span>
                    <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-red-600 rounded-full">
                      {metrics.processingTimeDistribution.slow}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white shadow rounded-lg border border-gray-200">
              <div className="px-6 py-4 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">Performance Metrics</h3>
              </div>
              <div className="px-6 py-4">
                <div className="space-y-4">
                  <div>
                    <div className="text-sm text-muted-foreground mb-1">Average Processing Time</div>
                    <div className="text-2xl font-bold">
                      {formatTime(metrics.averageProcessingTime)}
                    </div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground mb-1">Total Processing Time</div>
                    <div className="text-2xl font-bold">
                      {formatTime(metrics.totalProcessingTime)}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Last Updated */}
      <div className="text-center text-sm text-muted-foreground">
        Last updated: {new Date(dashboardData.timestamp).toLocaleString()}
      </div>
    </div>
  );
};

export default UploadMonitoringDashboard; 