import React, { useEffect, useRef } 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;
  functionId?: string; // AI function ID for tracking (e.g., "ai-cluster-01")
}

// Generate modal instance ID (increments per modal instance)
let modalInstanceCounter = 0;
const getModalInstanceId = () => {
  modalInstanceCounter++;
  return `modal-${String(modalInstanceCounter).padStart(2, '0')}`;
};

export default function ProgressModal({
  isOpen,
  title,
  percentage,
  status,
  message,
  details,
  onClose,
  onCancel,
  taskId,
  functionId,
}: ProgressModalProps) {
  // Generate modal instance ID on first render
  const modalInstanceIdRef = React.useRef<string | null>(null);
  React.useEffect(() => {
    if (!modalInstanceIdRef.current) {
      modalInstanceIdRef.current = getModalInstanceId();
    }
  }, []);
  
  const modalInstanceId = modalInstanceIdRef.current || 'modal-01';
  
  // Build full function ID with modal instance
  const fullFunctionId = functionId ? `${functionId}-${modalInstanceId}` : null;
  // Auto-close on completion after 2 seconds
  // Don't auto-close on error - let user manually close to see error details
  const hasAutoClosedRef = React.useRef(false);
  useEffect(() => {
    if (status === 'completed' && onClose && !hasAutoClosedRef.current) {
      hasAutoClosedRef.current = true;
      const timer = setTimeout(() => {
        onClose();
      }, 2000);
      return () => clearTimeout(timer);
    }
    // Reset when status changes away from completed
    if (status !== 'completed') {
      hasAutoClosedRef.current = false;
    }
    // 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>
        )}

        {/* Function ID and Task ID (for debugging) */}
        {(fullFunctionId || taskId) && import.meta.env.DEV && (
          <div className="mb-4 space-y-1 text-xs text-gray-400 dark:text-gray-600">
            {fullFunctionId && (
              <div>Function ID: {fullFunctionId}</div>
            )}
            {taskId && (
              <div>Task ID: {taskId}</div>
            )}
          </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>
  );
}

