import React, { useMemo } from 'react';
import { WorkflowStatusProps, WorkflowStatusType } from './WorkflowStatusTypes';
import styles from './WorkflowStatus.module.css';

// Helper function to extract workflow status and round from log message
const extractWorkflowStatus = (logs: any[]): { status: WorkflowStatusType; round: number | null; timestamp: number } => {
  // First, check for completion messages with success status (these take priority)
  const completionMessages = logs.filter(log => {
    const message = (log.message || '').toLowerCase();
    const logStatus = (log.status || '').toLowerCase();
    return (message.includes('fast path completed') || 
            message.includes('completed successfully')) &&
           logStatus === 'success';
  });

  // If we have completion messages, use the latest one
  if (completionMessages.length > 0) {
    const latestCompletion = completionMessages.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0))[0];
    
    // Try to extract round from completion message
    let round: number | null = null;
    const message = (latestCompletion.message || '').toLowerCase();
    const roundMatch = message.match(/\(?round\s+(\d+)\)?/i);
    if (roundMatch) {
      round = parseInt(roundMatch[1], 10);
    } else {
      // If no round in completion message, get round from latest workflow status message
      const statusMessages = logs.filter(log => {
        const msg = (log.message || '').toLowerCase();
        return msg.includes('workflow started') || msg.includes('workflow resumed');
      });
      if (statusMessages.length > 0) {
        const latestWorkflowStatus = statusMessages.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0))[0];
        const workflowMessage = (latestWorkflowStatus.message || '').toLowerCase();
        const workflowRoundMatch = workflowMessage.match(/\(?round\s+(\d+)\)?/i);
        if (workflowRoundMatch) {
          round = parseInt(workflowRoundMatch[1], 10);
        }
      }
    }

    return {
      status: 'completed',
      round,
      timestamp: latestCompletion.timestamp || 0
    };
  }

  // If no completion messages, look for workflow started/resumed/stopped messages
  const statusMessages = logs.filter(log => {
    const message = (log.message || '').toLowerCase();
    return message.includes('workflow started') || 
           message.includes('workflow resumed') || 
           message.includes('workflow stopped') ||
           message.includes('workflow failed') ||
           message.includes('workflow completed');
  });

  if (statusMessages.length === 0) {
    return { status: null, round: null, timestamp: 0 };
  }

  // Get the latest status message
  const latestStatus = statusMessages.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0))[0];
  const message = (latestStatus.message || '').toLowerCase();
  
  let status: WorkflowStatusType = null;
  if (message.includes('started')) {
    status = 'started';
  } else if (message.includes('resumed')) {
    status = 'resumed';
  } else if (message.includes('stopped')) {
    status = 'stopped';
  } else if (message.includes('failed')) {
    status = 'failed';
  } else if (message.includes('completed')) {
    status = 'completed';
  }

  // Extract round number from message (e.g., "round 4", "round 2", or "(round 4)")
  const roundMatch = message.match(/\(?round\s+(\d+)\)?/i);
  const round = roundMatch ? parseInt(roundMatch[1], 10) : null;

  return {
    status,
    round,
    timestamp: latestStatus.timestamp || 0
  };
};

// Helper function to format bytes to KB or MB
const formatBytes = (bytes?: number): string => {
  if (bytes === undefined || bytes === null) return '-';
  if (bytes === 0) return '0 B';
  const kb = bytes / 1024;
  if (kb < 1024) {
    return `${kb.toFixed(2)} KB`;
  }
  const mb = kb / 1024;
  return `${mb.toFixed(2)} MB`;
};

// Helper function to format price
const formatPrice = (price?: number): string => {
  if (price === undefined || price === null) return '-';
  return `$${price.toFixed(2)}`;
};

// Helper function to format processing time
const formatProcessingTime = (time?: number): string => {
  if (time === undefined || time === null) return '-';
  return `${time.toFixed(2)}s`;
};

const WorkflowStatus: React.FC<WorkflowStatusProps> = ({
  className = '',
  logs = [],
  workflowStatus: workflowStatusFromApi,
  currentRound: currentRoundFromApi,
  isRunning,
  latestStats
}) => {
  // Use workflow status and round from API response, fallback to extracting from logs
  const workflowStatus = useMemo(() => {
    // If we have status from API, use it
    if (workflowStatusFromApi) {
      let status: WorkflowStatusType = null;
      const statusLower = workflowStatusFromApi.toLowerCase();
      
      if (statusLower === 'completed') {
        status = 'completed';
      } else if (statusLower === 'running') {
        // Check if it's started or resumed from logs
        const startedResumedLogs = logs.filter(log => {
          const message = (log.message || '').toLowerCase();
          return message.includes('workflow started') || message.includes('workflow resumed');
        });
        if (startedResumedLogs.length > 0) {
          const latest = startedResumedLogs.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0))[0];
          const message = (latest.message || '').toLowerCase();
          status = message.includes('resumed') ? 'resumed' : 'started';
        } else {
          status = 'started';
        }
      } else if (statusLower === 'stopped') {
        status = 'stopped';
      } else if (statusLower === 'failed') {
        status = 'failed';
      }
      
      return {
        status,
        round: currentRoundFromApi || null,
        timestamp: Date.now() / 1000 // Use current time since we don't have timestamp from API
      };
    }
    
    // Fallback to extracting from logs
    return extractWorkflowStatus(logs);
  }, [workflowStatusFromApi, currentRoundFromApi, logs]);

  // Determine if workflow is running (show spinner)
  // Show spinner if explicitly running OR if status indicates running state
  const showSpinner = isRunning === true || workflowStatus.status === 'started' || workflowStatus.status === 'resumed';

  // Don't render if no status information and no stats (but always show if spinner should be visible)
  if (!showSpinner && !workflowStatus.status && workflowStatus.round === null && !latestStats) {
    return null;
  }

  return (
    <div className={`${styles.workflowStatusContainer} ${className}`}>
      {/* Status and Round Badges */}
      <div className={styles.workflowStatus}>
        {showSpinner && (
          <div className={styles.spinner} aria-label="Workflow running" />
        )}
        {workflowStatus.status && (
          <span className={styles.statusBadge} data-status={workflowStatus.status}>
            {workflowStatus.status.charAt(0).toUpperCase() + workflowStatus.status.slice(1)}
          </span>
        )}
        {workflowStatus.round !== null && (
          <span className={styles.roundBadge}>Round {workflowStatus.round}</span>
        )}
      </div>

      {/* Stats Display */}
      {latestStats && (
        <div className={styles.statsContainer}>
          {latestStats.priceUsd !== undefined && (
            <div className={styles.statItem}>
              <span className={styles.statLabel}>Price:</span>
              <span className={styles.statValue}>{formatPrice(latestStats.priceUsd)}</span>
            </div>
          )}
          {latestStats.processingTime !== undefined && (
            <div className={styles.statItem}>
              <span className={styles.statLabel}>Time:</span>
              <span className={styles.statValue}>{formatProcessingTime(latestStats.processingTime)}</span>
            </div>
          )}
          {latestStats.bytesSent !== undefined && (
            <div className={styles.statItem}>
              <span className={styles.statLabel}>Sent:</span>
              <span className={styles.statValue}>{formatBytes(latestStats.bytesSent)}</span>
            </div>
          )}
          {latestStats.bytesReceived !== undefined && (
            <div className={styles.statItem}>
              <span className={styles.statLabel}>Received:</span>
              <span className={styles.statValue}>{formatBytes(latestStats.bytesReceived)}</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default WorkflowStatus;

