import Table from 'cli-table3'
import chalk from 'chalk'

export function formatTable(data, columns) {
  // Handle empty result sets
  if (data.length === 0) {
    return chalk.gray('No results')
  }
  
  const table = new Table({
    head: columns.map(c => chalk.cyan(c.toUpperCase())),
    style: { 
      'padding-left': 1, 
      'padding-right': 1,
      border: ['gray']
    },
    chars: {
      'top': '─', 'top-mid': '┬', 'top-left': '┌', 'top-right': '┐',
      'bottom': '─', 'bottom-mid': '┴', 'bottom-left': '└', 'bottom-right': '┘',
      'left': '│', 'left-mid': '├', 'mid': '─', 'mid-mid': '┼',
      'right': '│', 'right-mid': '┤', 'middle': '│'
    }
  })
  
  data.forEach(row => {
    table.push(columns.map(col => {
      const value = String(row[col] ?? 'N/A')
      
      // Apply semantic coloring
      switch(col) {
        case 'status':
          if (value === 'RUNNING') return chalk.green(value)
          if (value === 'PENDING') return chalk.yellow(value)
          if (value === 'TERMINATED') return chalk.red(value)
          return value
          
        case 'available':
          if (value === '0') return chalk.gray(value)
          if (parseInt(value) > 10) return chalk.green(value)
          return value
          
        case 'type':
          if (value.includes('a100')) return chalk.magenta(value)
          if (value.includes('h100')) return chalk.blue(value)
          return value
          
        case 'price':
          return chalk.yellow(value)
          
        case 'ip':
          return value === 'N/A' ? chalk.gray(value) : chalk.green(value)
          
        default:
          return value
      }
    }))
  })
  
  return table.toString()
}

export function formatInstance(instance) {
  // Build formatted instance details
  const lines = []
  
  lines.push(`${chalk.gray('Instance:')} ${chalk.cyan(instance.id)}`)
  lines.push(`${chalk.gray('Type:')} ${instance.type}`)
  
  if (instance.status === 'PROVISIONING') {
    lines.push(`${chalk.gray('Status:')} ${chalk.yellow(instance.status)}`)
    
    // Display provisioning progress
    const progress = 40  // Estimate based on typical provisioning time
    const barLength = 20
    const filled = Math.floor(barLength * progress / 100)
    const bar = chalk.cyan('█'.repeat(filled)) + chalk.gray('░'.repeat(barLength - filled))
    lines.push(`${chalk.gray('Progress:')} ${bar} ${progress}%`)
    lines.push(`${chalk.gray('Elapsed:')} 4m 32s`)
    lines.push(`${chalk.gray('Estimated remaining:')} 6-8 minutes`)
  } else if (instance.status === 'RUNNING') {
    lines.push(`${chalk.gray('Status:')} ${chalk.green(instance.status + ' ✓')}`)
    lines.push(`${chalk.gray('IP:')} ${chalk.yellow(instance.ip)}`)
    lines.push(`${chalk.gray('SSH:')} ubuntu@${chalk.yellow(instance.ip)}`)
    lines.push(`${chalk.gray('Region:')} ${instance.region}`)
    lines.push(`${chalk.gray('Ready since:')} 2 minutes ago`)
  } else {
    lines.push(`${chalk.gray('Status:')} ${formatStatus(instance.status)}`)
    lines.push(`${chalk.gray('IP:')} ${instance.ip ? chalk.green(instance.ip) : chalk.gray('Pending...')}`)
    lines.push(`${chalk.gray('Region:')} ${instance.region}`)
  }
  
  if (instance.created && instance.status !== 'RUNNING') {
    lines.push(`${chalk.gray('Created:')} ${new Date(instance.created).toLocaleString()}`)
  }
  
  return lines.join('\n')
}

function formatStatus(status) {
  switch(status) {
    case 'RUNNING': return chalk.green(status)
    case 'PENDING': return chalk.yellow(status)
    case 'TERMINATED': return chalk.red(status)
    case 'NOT_FOUND': return chalk.red('NOT FOUND')
    default: return status
  }
}

export function formatError(error) {
  // Extract error message from API response or native error
  const message = error.response?.body?.message || error.message
  return chalk.red(`Error: ${message}`)
}