import React, { useEffect } from 'react';
import { Modal } from '../ui/modal';
import { ProgressBar } from '../ui/progress';
import Button from '../ui/button/Button';

export interface ProgressModalProps {
  isOpen: boolean;
  title: string;
  percentage: number; // 0-100
  status: 'pending' | 'processing' | 'completed' | 'error';
  message: string;
  details?: {
    current: number;
    total: number;
    completed: number;
    currentItem?: string;
    phase?: string;
  };
  onClose?: () => void;
  onCancel?: () => void;
  taskId?: string;
}

export default function ProgressModal({
  isOpen,
  title,
  percentage,
  status,
  message,
  details,
  onClose,
  onCancel,
  taskId,
}: ProgressModalProps) {
  // Auto-close on completion after 2 seconds
  // Don't auto-close on error - let user manually close to see error details
  useEffect(() => {
    if (status === 'completed' && onClose) {
      const timer = setTimeout(() => {
        onClose();
      }, 2000);
      return () => clearTimeout(timer);
    }
    // Don't auto-close on error - user should manually dismiss
  }, [status, onClose]);

  // Determine color based on status
  const getProgressColor = (): 'primary' | 'success' | 'error' | 'warning' => {
    if (status === 'error') return 'error';
    if (status === 'completed') return 'success';
    if (status === 'processing') return 'primary';
    return 'primary';
  };

  // Get status icon
  const getStatusIcon = () => {
    if (status === 'completed') {
      return (
        <svg
          className="w-6 h-6 text-success-500"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M5 13l4 4L19 7"
          />
        </svg>
      );
    }
    if (status === 'error') {
      return (
        <svg
          className="w-6 h-6 text-error-500"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M6 18L18 6M6 6l12 12"
          />
        </svg>
      );
    }
    // Processing/Pending - spinner
    return (
      <svg
        className="w-6 h-6 text-brand-500 animate-spin"
        fill="none"
        viewBox="0 0 24 24"
      >
        <circle
          className="opacity-25"
          cx="12"
          cy="12"
          r="10"
          stroke="currentColor"
          strokeWidth="4"
        />
        <path
          className="opacity-75"
          fill="currentColor"
          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
        />
      </svg>
    );
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose || (() => {})}
      className="max-w-lg"
      showCloseButton={status === 'completed' || status === 'error'}
    >
      <div className="p-6">
        {/* Header */}
        <div className="flex items-start gap-4 mb-6">
          <div className="flex-shrink-0 mt-1">{getStatusIcon()}</div>
          <div className="flex-1">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">
              {title}
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400">{message}</p>
          </div>
        </div>

        {/* Progress Bar */}
        <div className="mb-6">
          <ProgressBar
            value={percentage}
            color={getProgressColor()}
            size="lg"
            showLabel={true}
            label={`${Math.round(percentage)}%`}
          />
        </div>

        {/* Details */}
        {details && (
          <div className="mb-6 space-y-2">
            {details.currentItem && (
              <div className="text-sm text-gray-700 dark:text-gray-300">
                <span className="font-medium">Current:</span>{' '}
                <span className="text-gray-600 dark:text-gray-400">
                  {details.currentItem}
                </span>
              </div>
            )}
            {details.total > 0 && (
              <div className="text-sm text-gray-700 dark:text-gray-300">
                <span className="font-medium">Progress:</span>{' '}
                <span className="text-gray-600 dark:text-gray-400">
                  {details.current} of {details.total} completed
                </span>
              </div>
            )}
            {details.phase && (
              <div className="text-xs text-gray-500 dark:text-gray-500">
                Phase: {details.phase}
              </div>
            )}
          </div>
        )}

        {/* Task ID (for debugging) */}
        {taskId && import.meta.env.DEV && (
          <div className="mb-4 text-xs text-gray-400 dark:text-gray-600">
            Task ID: {taskId}
          </div>
        )}

        {/* Footer */}
        <div className="flex justify-end gap-3">
          {onCancel && status !== 'completed' && status !== 'error' && (
            <Button
              variant="secondary"
              size="sm"
              onClick={onCancel}
              disabled={status === 'processing'}
            >
              Cancel
            </Button>
          )}
          {(status === 'completed' || status === 'error') && onClose && (
            <Button variant="primary" size="sm" onClick={onClose}>
              {status === 'completed' ? 'Close' : 'Dismiss'}
            </Button>
          )}
        </div>
      </div>
    </Modal>
  );
}

