import React, { useState, useEffect } from 'react';
import { CheckCircle, AlertCircle, Clock, FileText, TrendingUp, Save } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';

interface ProcessingProgressProps {
  documentId: string;
  onComplete?: () => void;
  onError?: (error: string) => void;
}

interface ProgressData {
  documentId: string;
  jobId: string;
  status: 'uploading' | 'processing' | 'completed' | 'error';
  step: 'validation' | 'text_extraction' | 'analysis' | 'summary_generation' | 'storage';
  progress: number;
  message: string;
  startTime: string;
  estimatedTimeRemaining?: number;
  currentChunk?: number;
  totalChunks?: number;
  error?: string;
}

const ProcessingProgress: React.FC<ProcessingProgressProps> = ({
  documentId,
  onComplete,
  onError,
}) => {
  const { token } = useAuth();
  const [progress, setProgress] = useState<ProgressData | null>(null);
  const [isPolling, setIsPolling] = useState(true);

  const stepIcons = {
    validation: <CheckCircle className="h-4 w-4" />,
    text_extraction: <FileText className="h-4 w-4" />,
    analysis: <TrendingUp className="h-4 w-4" />,
    summary_generation: <FileText className="h-4 w-4" />,
    storage: <Save className="h-4 w-4" />,
  };

  const stepNames = {
    validation: 'Validation',
    text_extraction: 'Text Extraction',
    analysis: 'Analysis',
    summary_generation: 'Summary Generation',
    storage: 'Storage',
  };

  const stepColors = {
    validation: 'text-blue-600',
    text_extraction: 'text-green-600',
    analysis: 'text-purple-600',
    summary_generation: 'text-orange-600',
    storage: 'text-indigo-600',
  };

  useEffect(() => {
    // Guard against undefined or null document IDs
    if (!documentId || documentId === 'undefined' || documentId === 'null') {
      console.warn('ProcessingProgress: Invalid document ID:', documentId);
      return;
    }
    
    const pollProgress = async () => {
      try {
        const response = await fetch(`https://us-central1-cim-summarizer.cloudfunctions.net/api/documents/${documentId}/progress`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        });

        if (response.ok) {
          const data = await response.json();
          setProgress({
            documentId,
            jobId: data.jobId || '',
            status: data.status,
            step: data.step || 'validation',
            progress: data.progress || 0,
            message: data.message || '',
            startTime: data.startTime || new Date().toISOString(),
            estimatedTimeRemaining: data.estimatedTimeRemaining,
            currentChunk: data.currentChunk,
            totalChunks: data.totalChunks,
            error: data.error,
          });

          if (data.status === 'completed' || data.status === 'failed') {
            setIsPolling(false);
            if (data.status === 'completed') {
              onComplete?.();
            } else {
              onError?.(data.error || 'Processing failed');
            }
          }
        }
      } catch (error) {
        console.error('Failed to check progress:', error);
        setProgress(prev => prev ? {
          ...prev,
          message: 'Failed to check progress',
          error: 'Network error'
        } : null);
      }
    };

    // Poll every 2 seconds
    const interval = setInterval(() => {
      if (isPolling) {
        pollProgress();
      }
    }, 2000);

    // Initial poll
    pollProgress();

    return () => clearInterval(interval);
  }, [documentId, isPolling, onComplete, onError, token]);

  if (!progress) {
    return (
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-center space-x-3">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
          <div>
            <h3 className="text-lg font-medium text-gray-900">Initializing Processing</h3>
            <p className="text-sm text-gray-600">Setting up document processing...</p>
          </div>
        </div>
      </div>
    );
  }

  const formatTime = (seconds?: number) => {
    if (!seconds) return '';
    if (seconds < 60) return `${Math.round(seconds)}s`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.round(seconds % 60);
    return `${minutes}m ${remainingSeconds}s`;
  };

  const getStatusIcon = () => {
    switch (progress.status) {
      case 'completed':
        return <CheckCircle className="h-6 w-6 text-green-600" />;
      case 'error':
        return <AlertCircle className="h-6 w-6 text-red-600" />;
      default:
        return <Clock className="h-6 w-6 text-blue-600" />;
    }
  };

  const getStatusColor = () => {
    switch (progress.status) {
      case 'completed':
        return 'text-green-600';
      case 'error':
        return 'text-red-600';
      default:
        return 'text-blue-600';
    }
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center space-x-3">
          {getStatusIcon()}
          <div>
            <h3 className="text-lg font-medium text-gray-900">
              Document Processing
            </h3>
            <p className={`text-sm font-medium ${getStatusColor()}`}>
              {progress.status === 'completed' ? 'Completed' : 
               progress.status === 'error' ? 'Failed' : 'In Progress'}
            </p>
          </div>
        </div>
        {progress.estimatedTimeRemaining && (
          <div className="text-sm text-gray-500">
            Est. remaining: {formatTime(progress.estimatedTimeRemaining)}
          </div>
        )}
      </div>

      {/* Progress Bar */}
      <div className="mb-4">
        <div className="flex justify-between text-sm text-gray-600 mb-2">
          <span>{progress.message}</span>
          <span>{progress.progress}%</span>
        </div>
        <div className="w-full bg-gray-200 rounded-full h-3">
          <div
            className={`h-3 rounded-full transition-all duration-500 ease-out ${
              progress.status === 'error' ? 'bg-red-600' : 'bg-blue-600'
            }`}
            style={{ width: `${progress.progress}%` }}
          />
        </div>
      </div>

      {/* Current Step */}
      <div className="mb-4">
        <div className="flex items-center space-x-2 mb-2">
          <span className={stepColors[progress.step]}>
            {stepIcons[progress.step]}
          </span>
          <span className="text-sm font-medium text-gray-900">
            {stepNames[progress.step]}
          </span>
        </div>
        <p className="text-sm text-gray-600 ml-6">{progress.message}</p>
      </div>

      {/* Chunk Progress (if applicable) */}
      {progress.currentChunk && progress.totalChunks && (
        <div className="mb-4 p-3 bg-blue-50 rounded-lg">
          <div className="flex justify-between text-sm text-blue-700 mb-1">
            <span>Processing chunks</span>
            <span>{progress.currentChunk} / {progress.totalChunks}</span>
          </div>
          <div className="w-full bg-blue-200 rounded-full h-2">
            <div
              className="h-2 bg-blue-600 rounded-full transition-all duration-300"
              style={{ width: `${(progress.currentChunk / progress.totalChunks) * 100}%` }}
            />
          </div>
        </div>
      )}

      {/* Error Display */}
      {progress.error && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
          <div className="flex items-center space-x-2">
            <AlertCircle className="h-4 w-4 text-red-600" />
            <span className="text-sm font-medium text-red-800">Error</span>
          </div>
          <p className="text-sm text-red-700 mt-1">{progress.error}</p>
        </div>
      )}

      {/* Processing Steps Overview */}
      <div className="mt-4 pt-4 border-t border-gray-200">
        <h4 className="text-sm font-medium text-gray-900 mb-3">Processing Steps</h4>
        <div className="space-y-2">
          {Object.entries(stepNames).map(([step, name]) => {
            const isCompleted = progress.progress >= getStepProgress(step as keyof typeof stepNames);
            const isCurrent = progress.step === step;
            
            return (
              <div key={step} className="flex items-center space-x-2">
                <div className={`h-4 w-4 rounded-full border-2 ${
                  isCompleted ? 'bg-green-600 border-green-600' :
                  isCurrent ? 'bg-blue-600 border-blue-600' :
                  'bg-gray-200 border-gray-300'
                }`}>
                  {isCompleted && <CheckCircle className="h-3 w-3 text-white" />}
                </div>
                <span className={`text-sm ${
                  isCompleted ? 'text-green-600 font-medium' :
                  isCurrent ? 'text-blue-600 font-medium' :
                  'text-gray-500'
                }`}>
                  {name}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// Helper function to determine step progress
const getStepProgress = (step: string): number => {
  const stepOrder = ['validation', 'text_extraction', 'analysis', 'summary_generation', 'storage'];
  const stepIndex = stepOrder.indexOf(step);
  return stepIndex >= 0 ? (stepIndex + 1) * 20 : 0;
};

export default ProcessingProgress; 