'use client';

import { useEffect, useState } from 'react';

interface ProgressUpdate {
  type: 'progress' | 'completed' | 'error' | 'connected';
  current: number;
  total: number;
  message: string;
  url?: string;
  title?: string;
  author?: string;
  wordCount?: number;
  totalWordCount?: number;
  error?: string;
  sessionId?: string;
}

interface BulkImportProgressProps {
  sessionId: string;
  onComplete?: (data?: any) => void;
  onError?: (error: string) => void;
  combineMode?: boolean;
}

export default function BulkImportProgress({ 
  sessionId, 
  onComplete, 
  onError,
  combineMode = false 
}: BulkImportProgressProps) {
  const [progress, setProgress] = useState<ProgressUpdate>({
    type: 'progress',
    current: 0,
    total: 1,
    message: 'Connecting...'
  });
  const [isConnected, setIsConnected] = useState(false);
  const [recentActivities, setRecentActivities] = useState<string[]>([]);

  useEffect(() => {
    const eventSource = new EventSource(`/scrape/bulk/progress?sessionId=${sessionId}`);
    
    eventSource.onmessage = (event) => {
      try {
        const data: ProgressUpdate = JSON.parse(event.data);
        
        if (data.type === 'connected') {
          setIsConnected(true);
          return;
        }
        
        setProgress(data);
        
        // Add to recent activities (keep last 5)
        if (data.message) {
          setRecentActivities(prev => [
            data.message,
            ...prev.slice(0, 4)
          ]);
        }
        
        if (data.type === 'completed') {
          setTimeout(() => {
            onComplete?.(data);
            eventSource.close();
          }, 2000); // Show completion message for 2 seconds
        } else if (data.type === 'error') {
          onError?.(data.error || 'Unknown error occurred');
          eventSource.close();
        }
      } catch (error) {
        console.error('Failed to parse progress update:', error);
      }
    };

    eventSource.onerror = (error) => {
      console.error('EventSource error:', error);
      setIsConnected(false);
      onError?.('Connection to progress stream failed');
      eventSource.close();
    };

    return () => {
      eventSource.close();
    };
  }, [sessionId, onComplete, onError]);

  const progressPercentage = progress.total > 0 
    ? Math.round((progress.current / progress.total) * 100) 
    : 0;

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

  const getStatusIcon = () => {
    switch (progress.type) {
      case 'completed': return '✓';
      case 'error': return '✗';
      default: return null;
    }
  };

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-6">
      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-lg font-medium text-gray-900">
            {combineMode ? 'Combining Stories' : 'Bulk Import Progress'}
          </h3>
          <div className="flex items-center gap-2">
            {!isConnected && (
              <div className="h-2 w-2 bg-yellow-400 rounded-full animate-pulse"></div>
            )}
            <span className="text-sm text-gray-600">
              {progress.current} of {progress.total}
            </span>
          </div>
        </div>
        
        {/* Progress Bar */}
        <div className="w-full bg-gray-200 rounded-full h-3 mb-3">
          <div
            className={`h-3 rounded-full transition-all duration-500 ${getStatusColor()}`}
            style={{ width: `${progressPercentage}%` }}
          ></div>
        </div>
        
        {/* Progress Percentage */}
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-gray-900">
            {progressPercentage}%
          </span>
          {progress.type === 'completed' && (
            <span className="text-green-600 font-medium">
              {getStatusIcon()} Complete
            </span>
          )}
          {progress.type === 'error' && (
            <span className="text-red-600 font-medium">
              {getStatusIcon()} Error
            </span>
          )}
        </div>
      </div>

      {/* Current Status Message */}
      <div className="mb-4">
        <div className="flex items-center gap-2">
          {progress.type === 'progress' && (
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
          )}
          <p className="text-sm text-gray-700">{progress.message}</p>
        </div>
        
        {/* Word Count for Combine Mode */}
        {combineMode && progress.totalWordCount !== undefined && (
          <p className="text-sm text-gray-500 mt-1">
            Total words collected: {progress.totalWordCount.toLocaleString()}
          </p>
        )}
      </div>

      {/* Current URL being processed */}
      {progress.url && (
        <div className="mb-4 p-3 bg-gray-50 rounded-md">
          <p className="text-sm text-gray-600 mb-1">Currently processing:</p>
          <p className="text-sm font-mono text-gray-800 truncate">{progress.url}</p>
          {progress.title && progress.author && (
            <p className="text-sm text-gray-600 mt-1">
              "{progress.title}" by {progress.author}
              {progress.wordCount && (
                <span className="ml-2 text-gray-500">
                  ({progress.wordCount.toLocaleString()} words)
                </span>
              )}
            </p>
          )}
        </div>
      )}

      {/* Recent Activities */}
      {recentActivities.length > 0 && (
        <div>
          <h4 className="text-sm font-medium text-gray-900 mb-2">Recent Activity</h4>
          <div className="space-y-1 max-h-32 overflow-y-auto">
            {recentActivities.map((activity, index) => (
              <p
                key={index}
                className={`text-xs text-gray-600 ${
                  index === 0 ? 'font-medium text-gray-800' : ''
                }`}
              >
                {activity}
              </p>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}