const { getOrderDetails } = require('../api/pamsikaClient');
const { updateUserData, getUserData } = require('../utils/user');
const { sendMainMenu } = require('../utils/menuUtils');

/**
 * Handle orders flow
 * @param {Object} sock - WhatsApp socket
 * @param {string} phone - User's phone number
 * @param {Object} userData - User data
 * @param {string} message - User's message (optional)
 */
async function handleOrders(sock, phone, userData, message = '') {
  try {
    // First, check if we're in ORDERS_NO_ORDERS state and handling a response
    if (userData.state === 'ORDERS_NO_ORDERS' && message) {
      if (message === '1') {
        // Option 1: Browse Events
        await sock.sendMessage(phone, { text: "📋 Taking you to browse events... 🚀" });
        
        // We'll use the direct ticketing handler instead of trying to route through menu
        // This is more direct and avoids circular import issues
        const { handleTicketing } = require('./ticketing');
        
        // Reset any existing ticketing data
        await updateUserData(phone, { 
          state: 'TICKETING_START', 
          lastMessage: message,
          currentEvent: null,
          ticketData: null
        });
        
        // Call the ticketing handler with START command
        await handleTicketing(sock, phone, await getUserData(phone), 'START');
        return;
      } else if (message === '2') {
        // Option 2: Back to Main Menu
        await sock.sendMessage(phone, { text: "🏠 Taking you back to the main menu... 🚀" });
        await sendMainMenu(sock, phone, userData.name);
        await updateUserData(phone, { 
          state: 'MAIN_MENU', 
          lastMessage: message,
          currentEvent: null,
          ticketData: null
        });
        return;
      }
    }
    
    // If no orders in user data
    if (!userData.orders || userData.orders.length === 0) {
      await sock.sendMessage(phone, {
        text: "📭 You don't have any orders yet. Would you like to browse available events? 🎫\n\n1️⃣ *Browse Events* 📋\n2️⃣ *Back to Main Menu* 🏠"
      });
      
      // Update state to handle navigation
      await updateUserData(phone, { 
        state: 'ORDERS_NO_ORDERS', 
        lastMessage: message,
        currentEvent: null,
        ticketData: null
      });
      return;
    }
    
    // If user has orders, show the list
    if (!message) {
      // Initial order display - show list of orders
      const ordersList = userData.orders
        .map((order, index) => {
          const date = new Date(order.timestamp).toLocaleDateString();
          return `${index + 1}. Order #${order.orderId} - ${order.event.product_name} (${order.quantity} tickets) - ${date}`;
        })
        .join('\n\n');
      
      await sock.sendMessage(phone, {
        text: `📦 *Your Orders*\n\n${ordersList}\n\n🔢 Reply with the number of the order to see details, or type 'menu' to go back to the main menu. 🏠`
      });
      
      await updateUserData(phone, { state: 'ORDERS_LIST', lastMessage: message });
      return;
    }
    
    // Handle different states in the orders flow
    switch (userData.state) {
      case 'ORDERS_NO_ORDERS':
        if (message === '1') {
          try {
            // Use the direct ticketing handler for Browse Events
            const { handleTicketing } = require('./ticketing');
            
            // First update the state
            await updateUserData(phone, { 
              state: 'TICKETING_START',
              lastMessage: message,
              currentEvent: null,
              ticketData: null
            });
            
            await sock.sendMessage(phone, { text: "📋 Taking you to browse events... 🚀" });
            
            // Get updated user data and call ticketing handler
            const updatedUserData = await getUserData(phone);
            await handleTicketing(sock, phone, updatedUserData, 'START');
          } catch (error) {
            console.error('Error in browse events flow:', error);
            await sock.sendMessage(phone, { text: "Error browsing events. Please try again later." });
            
            // Fallback to main menu
            await updateUserData(phone, { 
              state: 'MAIN_MENU', 
              lastMessage: message,
              currentEvent: null,
              ticketData: null
            });
            await sendMainMenu(sock, phone, userData.name);
          }
          return;
        } else if (message === '2') {
          // Back to main menu - completely reset the state
          await sock.sendMessage(phone, { text: "🏠 Taking you back to the main menu... 🚀" });
          
          // First update the state to avoid conflicts
          await updateUserData(phone, { 
            state: 'MAIN_MENU', 
            lastMessage: message,
            currentEvent: null,
            ticketData: null
          });
          
          // Then show the main menu
          await sendMainMenu(sock, phone, userData.name);
          return;
        }
        return;
        
      case 'ORDERS_LIST':
        if (message.toLowerCase() === 'menu') {
          // Back to main menu
          await sock.sendMessage(phone, { text: "🏠 Taking you back to the main menu... 🚀" });
          await sendMainMenu(sock, phone, userData.name);
          await updateUserData(phone, { state: 'MAIN_MENU', lastMessage: message });
          return;
        }
        
        // Try to parse order number
        const orderIndex = parseInt(message) - 1;
        if (isNaN(orderIndex) || orderIndex < 0 || orderIndex >= userData.orders.length) {
          await sock.sendMessage(phone, {
            text: `❌ *Invalid Order Number!* Please choose a number between 1 and ${userData.orders.length}, or type 'menu' to go back. 🏠`
          });
          return;
        }
        
        // Get order details from API
        try {
          const order = userData.orders[orderIndex];
          const orderDetailsFromAPI = await getOrderDetails(order.orderId);
          
          // Format order details
          let orderDetails = `📦 *Order #${order.orderId}*\n\n`;
          orderDetails += `Event: ${order.event.product_name}\n`;
          orderDetails += `Quantity: ${order.quantity} 🎫\n`;
          orderDetails += `Date Purchased: ${new Date(order.timestamp).toLocaleDateString()} 📅\n`;
          orderDetails += `Event Date: ${order.event.product_date_created ? new Date(order.event.product_date_created).toLocaleDateString() : 'Not specified'} 📅\n`;
          orderDetails += `Total Price: ${order.event.product_price * order.quantity} MWK 💰\n`;
          if (order.paymentMethod) {
            orderDetails += `Payment Method: ${order.paymentMethod} 💳\n\n`;
          } else {
            orderDetails += `\n`;
          }
          
          // Add API details if available
          if (orderDetailsFromAPI && Array.isArray(orderDetailsFromAPI) && orderDetailsFromAPI.length > 0) {
            const apiDetails = orderDetailsFromAPI[0];
            orderDetails += `Status: ${apiDetails.status || 'Confirmed'}\n`;
            if (apiDetails.payment_method && !order.paymentMethod) {
              orderDetails += `Payment Method: ${apiDetails.payment_method}\n`;
            }
            if (apiDetails.venue) {
              orderDetails += `Venue: ${apiDetails.venue}\n`;
            }
          }
          
          orderDetails += `\nReply with:\n1️⃣ *Back to Orders*\n2️⃣ *Main Menu*`;
          
          // Send order details
          await sock.sendMessage(phone, { text: orderDetails });
          await updateUserData(phone, { 
            state: 'ORDERS_DETAILS',
            currentOrderIndex: orderIndex,
            lastMessage: message 
          });
        } catch (error) {
          console.error('Error fetching order details:', error);
          await sock.sendMessage(phone, {
            text: "⚠️ Sorry, I couldn't retrieve the details for this order. Would you like to:\n\n1️⃣ *Go back to your orders* 📦\n2️⃣ *Return to main menu* 🏠"
          });
          await updateUserData(phone, { state: 'ORDERS_ERROR', lastMessage: message });
        }
        break;
        
      case 'ORDERS_DETAILS':
        if (message === '1') {
          // Back to orders list
          await handleOrders(sock, phone, userData);
          await updateUserData(phone, { state: 'ORDERS_LIST', lastMessage: message });
        } else if (message === '2') {
          // Back to main menu
          await sock.sendMessage(phone, { text: "🏠 Taking you back to the main menu... 🚀" });
          await sendMainMenu(sock, phone, userData.name);
          await updateUserData(phone, { state: 'MAIN_MENU', lastMessage: message });
        } else {
          // Invalid response
          await sock.sendMessage(phone, {
            text: "🔢 Please reply with 1 to go back to your orders or 2 to return to the main menu."
          });
        }
        break;
        
      case 'ORDERS_ERROR':
        if (message === '1') {
          // Back to orders list
          await handleOrders(sock, phone, userData);
          await updateUserData(phone, { state: 'ORDERS_LIST', lastMessage: message });
        } else if (message === '2') {
          // Back to main menu
          await sock.sendMessage(phone, { text: "🏠 Taking you back to the main menu... 🚀" });
          await sendMainMenu(sock, phone, userData.name);
          await updateUserData(phone, { state: 'MAIN_MENU', lastMessage: message });
        } else {
          // Invalid response
          await sock.sendMessage(phone, {
            text: "🔢 Please reply with 1 to go back to your orders or 2 to return to the main menu."
          });
        }
        break;
        
      default:
        // Unknown orders state, reset to main menu
        await sock.sendMessage(phone, {
          text: "🤔 I seem to have lost track of our orders process. 🔄 Let's start over with the main menu. 🏠"
        });
        await sendMainMenu(sock, phone, userData.name);
        await updateUserData(phone, { state: 'MAIN_MENU', lastMessage: message });
    }
  } catch (error) {
    console.error('Error in orders flow:', error);
    await sock.sendMessage(phone, {
      text: "⚠️ *Oops!* Sorry, I encountered an error while retrieving your orders. 🙏 Please try again or type #startover to reset our conversation. 🔄"
    });
    await updateUserData(phone, { state: 'MAIN_MENU', lastMessage: message });
  }
}

module.exports = {
  handleOrders
};
