import React, { useState, useEffect } from 'react';
import { ImageProcessingProgressTracker, ImageProcessingProgress } from '../utils/imageProcessingProgress';

interface ImageProcessingProgressProps {
  storyId: string;
  autoStart?: boolean;
  onComplete?: () => void;
  onError?: (error: string) => void;
}

export const ImageProcessingProgressComponent: React.FC<ImageProcessingProgressProps> = ({
  storyId,
  autoStart = false,
  onComplete,
  onError
}) => {
  const [progress, setProgress] = useState<ImageProcessingProgress | null>(null);
  const [isTracking, setIsTracking] = useState(false);
  const [tracker, setTracker] = useState<ImageProcessingProgressTracker | null>(null);

  const startTracking = () => {
    if (tracker) {
      tracker.stop();
    }

    const newTracker = new ImageProcessingProgressTracker(storyId);

    newTracker.onProgress((progress) => {
      setProgress(progress);
    });

    newTracker.onComplete((finalProgress) => {
      setProgress(finalProgress);
      setIsTracking(false);
      onComplete?.();
    });

    newTracker.onError((error) => {
      console.error('Image processing error:', error);
      setIsTracking(false);
      onError?.(error);
    });

    setTracker(newTracker);
    setIsTracking(true);
    newTracker.start();
  };

  const stopTracking = () => {
    if (tracker) {
      tracker.stop();
      setIsTracking(false);
    }
  };

  useEffect(() => {
    if (autoStart) {
      startTracking();
    }

    return () => {
      if (tracker) {
        tracker.stop();
      }
    };
  }, [storyId, autoStart]);

  if (!progress && !isTracking) {
    return null;
  }

  if (!progress?.isProcessing && !progress?.completed) {
    return null;
  }

  return (
    <div className="image-processing-progress">
      <div className="progress-header">
        <h4>Processing Images</h4>
        {isTracking && (
          <button onClick={stopTracking} className="btn btn-sm btn-secondary">
            Cancel
          </button>
        )}
      </div>

      {progress && (
        <div className="progress-content">
          {progress.error ? (
            <div className="alert alert-danger">
              <strong>Error:</strong> {progress.error}
            </div>
          ) : progress.completed ? (
            <div className="alert alert-success">
              <strong>Completed:</strong> {progress.status}
            </div>
          ) : (
            <div className="progress-info">
              <div className="status-text">
                <strong>Status:</strong> {progress.status}
              </div>

              <div className="progress-stats">
                Processing {progress.processedImages} of {progress.totalImages} images
                ({progress.progressPercentage.toFixed(1)}%)
              </div>

              {progress.currentImageUrl && (
                <div className="current-image">
                  <strong>Current:</strong>
                  <span className="image-url" title={progress.currentImageUrl}>
                    {progress.currentImageUrl.length > 60
                      ? `...${progress.currentImageUrl.slice(-60)}`
                      : progress.currentImageUrl
                    }
                  </span>
                </div>
              )}

              {/* Progress bar */}
              <div className="progress-bar-container">
                <div className="progress-bar">
                  <div
                    className="progress-bar-fill"
                    style={{ width: `${progress.progressPercentage}%` }}
                  />
                </div>
                <span className="progress-percentage">
                  {progress.progressPercentage.toFixed(1)}%
                </span>
              </div>
            </div>
          )}
        </div>
      )}

      <style jsx>{`
        .image-processing-progress {
          background: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 4px;
          padding: 1rem;
          margin: 1rem 0;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        }

        .progress-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 0.75rem;
        }

        .progress-header h4 {
          margin: 0;
          font-size: 1.1rem;
          color: #495057;
        }

        .progress-content {
          space-y: 0.5rem;
        }

        .status-text {
          font-size: 0.9rem;
          color: #6c757d;
          margin-bottom: 0.5rem;
        }

        .progress-stats {
          font-weight: 500;
          color: #495057;
          margin-bottom: 0.5rem;
        }

        .current-image {
          font-size: 0.85rem;
          color: #6c757d;
          margin-bottom: 0.75rem;
        }

        .image-url {
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
          background: #e9ecef;
          padding: 0.1rem 0.3rem;
          border-radius: 2px;
          margin-left: 0.5rem;
        }

        .progress-bar-container {
          display: flex;
          align-items: center;
          gap: 0.75rem;
        }

        .progress-bar {
          flex: 1;
          height: 8px;
          background: #e9ecef;
          border-radius: 4px;
          overflow: hidden;
        }

        .progress-bar-fill {
          height: 100%;
          background: linear-gradient(90deg, #007bff, #0056b3);
          transition: width 0.3s ease;
        }

        .progress-percentage {
          font-size: 0.85rem;
          font-weight: 500;
          color: #495057;
          min-width: 3rem;
          text-align: right;
        }

        .btn {
          padding: 0.25rem 0.5rem;
          border-radius: 3px;
          border: 1px solid transparent;
          cursor: pointer;
          font-size: 0.8rem;
        }

        .btn-secondary {
          background: #6c757d;
          color: white;
          border-color: #6c757d;
        }

        .btn-secondary:hover {
          background: #5a6268;
          border-color: #545b62;
        }

        .alert {
          padding: 0.75rem;
          border-radius: 4px;
          margin-bottom: 0.5rem;
        }

        .alert-danger {
          background: #f8d7da;
          color: #721c24;
          border: 1px solid #f5c6cb;
        }

        .alert-success {
          background: #d4edda;
          color: #155724;
          border: 1px solid #c3e6cb;
        }
      `}</style>
    </div>
  );
};

export default ImageProcessingProgressComponent;