import chalk from 'chalk';
import { loadCredentials } from '../lib/credentials.js';
import { getMessages } from '../lib/api.js';

function formatPhone(phone) {
  if (!phone) return 'Unknown';
  // Format as (XXX) XXX-XXXX if it's a US number
  const digits = phone.replace(/\D/g, '');
  if (digits.length === 11 && digits.startsWith('1')) {
    return `(${digits.slice(1, 4)}) ${digits.slice(4, 7)}-${digits.slice(7)}`;
  }
  if (digits.length === 10) {
    return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
  }
  return phone;
}

function formatDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const now = new Date();
  const diffMs = now - date;
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);
  
  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  if (diffDays < 7) return `${diffDays}d ago`;
  
  return date.toLocaleDateString();
}

function truncate(str, len) {
  if (!str) return '';
  if (str.length <= len) return str;
  return str.substring(0, len - 3) + '...';
}

export async function messagesCommand(options) {
  const credentials = await loadCredentials();
  
  if (!credentials) {
    console.log(chalk.red('\n❌ Not authenticated. Run `textnow auth` first.\n'));
    process.exit(1);
  }
  
  const limit = parseInt(options.limit) || 20;
  
  console.log(chalk.cyan.bold('\n📬 Recent Messages\n'));
  console.log(chalk.gray('Fetching messages...\n'));
  
  try {
    const data = await getMessages(limit);
    
    // Handle different response formats
    let conversations = [];
    if (Array.isArray(data)) {
      conversations = data;
    } else if (data.conversations) {
      conversations = data.conversations;
    } else if (data.messages) {
      conversations = data.messages;
    } else if (data.result) {
      conversations = Array.isArray(data.result) ? data.result : [data.result];
    }
    
    if (conversations.length === 0) {
      console.log(chalk.yellow('No messages found.\n'));
      return;
    }
    
    console.log(chalk.gray('─────────────────────────────────────────────────────────────────'));
    
    conversations.slice(0, limit).forEach((conv, index) => {
      // Handle different data structures
      const contact = conv.contact_value || conv.contact || conv.number || conv.phone_number || conv.to || conv.from || 'Unknown';
      const lastMessage = conv.message || conv.last_message || conv.body || conv.text || '';
      const timestamp = conv.date || conv.timestamp || conv.created_at || conv.received_at || '';
      const isRead = conv.read !== false && conv.is_read !== false;
      const direction = conv.message_direction || conv.direction || (conv.incoming ? 'incoming' : 'outgoing');
      
      const readIndicator = isRead ? chalk.gray('○') : chalk.blue('●');
      const dirIndicator = direction === 'incoming' || direction === 'in' ? chalk.green('←') : chalk.cyan('→');
      
      console.log(
        `${readIndicator} ${dirIndicator} ` +
        chalk.white(formatPhone(contact).padEnd(16)) + ' ' +
        chalk.gray(formatDate(timestamp).padEnd(10)) + ' ' +
        chalk.white(truncate(lastMessage, 40))
      );
    });
    
    console.log(chalk.gray('─────────────────────────────────────────────────────────────────'));
    console.log(chalk.gray(`\nShowing ${Math.min(conversations.length, limit)} conversations\n`));
    
  } catch (error) {
    console.log(chalk.red('❌ Failed to fetch messages:'));
    console.log(chalk.red(`   ${error.message}`));
    
    if (error.message.includes('401') || error.message.includes('403')) {
      console.log(chalk.yellow('\n💡 Your session may have expired. Try running `textnow auth` again.\n'));
    }
    
    process.exit(1);
  }
}
