/**
 * Current Processing Card Component
 * Shows real-time automation progress with currently processing items
 */
import React, { useEffect, useState } from 'react';
import { automationService, ProcessingState } from '../../services/automationService';

interface CurrentProcessingCardProps {
  runId: string;
  siteId: number;
  currentStage: number;
  onComplete?: () => void;
}

const CurrentProcessingCard: React.FC<CurrentProcessingCardProps> = ({
  runId,
  siteId,
  currentStage,
  onComplete,
}) => {
  const [processingState, setProcessingState] = useState<ProcessingState | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    const fetchState = async () => {
      try {
        const state = await automationService.getCurrentProcessing(siteId, runId);
        
        if (!isMounted) return;

        setProcessingState(state);
        setError(null);

        // If stage completed (all items processed), trigger refresh
        if (state && state.processed_items >= state.total_items && state.total_items > 0) {
          onComplete?.();
        }
      } catch (err) {
        if (!isMounted) return;
        console.error('Error fetching processing state:', err);
        setError('Failed to load processing state');
      }
    };

    // Initial fetch
    fetchState();

    // Poll every 3 seconds
    const interval = setInterval(fetchState, 3000);

    return () => {
      isMounted = false;
      clearInterval(interval);
    };
  }, [siteId, runId, onComplete]);

  if (error) {
    return (
      <div className="bg-red-50 dark:bg-red-900/20 border-2 border-red-500 rounded-lg p-4 mb-6">
        <p className="text-red-700 dark:text-red-300 text-sm">{error}</p>
      </div>
    );
  }

  if (!processingState) {
    return null;
  }

  const percentage = processingState.percentage;

  return (
    <div className="bg-blue-50 dark:bg-blue-900/20 border-2 border-blue-500 rounded-lg p-6 mb-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="animate-pulse">
            <svg
              className="w-8 h-8 text-blue-600 dark:text-blue-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 10V3L4 14h7v7l9-11h-7z"
              />
            </svg>
          </div>
          <div>
            <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
              Automation In Progress
            </h2>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              Stage {currentStage}: {processingState.stage_name}
              <span className="ml-2 px-2 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded text-xs">
                {processingState.stage_type}
              </span>
            </p>
          </div>
        </div>
        <div className="text-right">
          <div className="text-4xl font-bold text-blue-600 dark:text-blue-400">
            {percentage}%
          </div>
          <div className="text-sm text-gray-600 dark:text-gray-400">
            {processingState.processed_items}/{processingState.total_items} processed
          </div>
        </div>
      </div>

      {/* Progress Bar */}
      <div className="mb-6">
        <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3">
          <div
            className="bg-blue-600 dark:bg-blue-500 h-3 rounded-full transition-all duration-500"
            style={{ width: `${Math.min(percentage, 100)}%` }}
          />
        </div>
      </div>

      {/* Currently Processing and Up Next */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Currently Processing */}
        <div>
          <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
            Currently Processing:
          </h3>
          <div className="space-y-1">
            {processingState.currently_processing.length > 0 ? (
              processingState.currently_processing.map((item, idx) => (
                <div key={idx} className="flex items-start gap-2 text-sm">
                  <span className="text-blue-600 dark:text-blue-400 mt-1">•</span>
                  <span className="text-gray-800 dark:text-gray-200 font-medium line-clamp-2">
                    {item.title}
                  </span>
                </div>
              ))
            ) : (
              <div className="text-sm text-gray-500 dark:text-gray-400 italic">
                No items currently processing
              </div>
            )}
          </div>
        </div>

        {/* Up Next */}
        <div>
          <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
            Up Next:
          </h3>
          <div className="space-y-1">
            {processingState.up_next.length > 0 ? (
              <>
                {processingState.up_next.map((item, idx) => (
                  <div key={idx} className="flex items-start gap-2 text-sm">
                    <span className="text-gray-400 dark:text-gray-500 mt-1">•</span>
                    <span className="text-gray-600 dark:text-gray-400 line-clamp-2">
                      {item.title}
                    </span>
                  </div>
                ))}
                {processingState.remaining_count > processingState.up_next.length + processingState.currently_processing.length && (
                  <div className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                    + {processingState.remaining_count - processingState.up_next.length - processingState.currently_processing.length} more in queue
                  </div>
                )}
              </>
            ) : (
              <div className="text-sm text-gray-500 dark:text-gray-400 italic">
                Queue empty
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CurrentProcessingCard;
