/**
 * WhatsApp Instances Management
 * Handles instance creation, connection, and management with Evolution API
 */

console.log('✅ whatsapp-instances.js loaded - version 2.0');
window.WHATSAPP_INSTANCES_LOADED = true;

let currentInstances = [];
let selectedInstanceType = 'whatsapp_web';
let socket = null;
let waitingForQR = false; // Flag to control QR modal

/**
 * Translate elements with data-i18n attributes
 */
function translatePage() {
  if (!window.i18next || !window.i18next.isInitialized) {
    console.warn('i18next not initialized yet');
    return;
  }
  
  console.log('Translating page with language:', i18next.language);
  
  document.querySelectorAll('[data-i18n]').forEach(element => {
    const key = element.getAttribute('data-i18n');
    
    // Check if it's a placeholder translation [placeholder]key
    if (key.startsWith('[placeholder]')) {
      const actualKey = key.replace('[placeholder]', '');
      const translation = i18next.t(actualKey);
      if (translation && translation !== actualKey) {
        element.placeholder = translation;
      }
    } else {
      // Regular text translation
      const translation = i18next.t(key);
      if (translation && translation !== key) {
        element.textContent = translation;
      }
    }
  });
}

// Initialize on page load
$(document).ready(function() {
  // Check authentication
  const token = localStorage.getItem('token');
  if (!token) {
    window.location.href = '/login';
    return;
  }
  
  // Wait for i18next to initialize, then translate
  const checkI18n = setInterval(() => {
    if (window.i18next && window.i18next.isInitialized) {
      clearInterval(checkI18n);
      translatePage();
      
      // Initialize Socket.IO for real-time updates
      initializeSocket();
      
      // Load instances
      loadInstances();
      
      // Set up periodic refresh
      setInterval(loadInstances, 10000); // Refresh every 10 seconds
      
      // Add listener for QR modal close
      $('#qrCodeModal').on('hidden.bs.modal', function () {
        console.log('QR modal closed by user');
        closeQRModal();
      });
    }
  }, 100);
});

/**
 * Initialize Socket.IO connection
 */
function initializeSocket() {
  const token = localStorage.getItem('token');
  const tenantId = getTenantIdFromToken();
  
  if (!tenantId) return;
  
  // Connect to tenant namespace
  socket = io(`/tenant/${tenantId}`, {
    auth: { token }
  });
  
  socket.on('connect', () => {
    console.log('Socket connected to tenant namespace');
  });
  
  // Listen for QR code updates
  socket.on('qr-code', (data) => {
    console.log('QR code event received:', typeof data, data);
    
    if (!waitingForQR) {
      console.log('Not waiting for QR, ignoring');
      return;
    }
    
    let qrCode = null;
    let instanceId = null;
    
    // Handle different data formats
    if (typeof data === 'string' && data) {
      qrCode = data;
    } else if (data && typeof data === 'object') {
      qrCode = data.qrCode || data.qrcode || data.qr || data.base64 || data.code;
      instanceId = data.instanceId || data.instance_id || lastInstanceId;
    }
    
    if (qrCode) {
      console.log('Showing QR code from socket');
      showQRCodeData(qrCode, instanceId);
    } else {
      console.log('No valid QR code in socket data');
    }
  });
  
  // Listen for connection status updates
  socket.on('connection-update', (data) => {
    console.log('Connection update received:', data);
    
    // Close QR modal if connection is established
    if (data.status === 'connected' || data.state === 'open' || data.status === 'open') {
      console.log('Connection established, closing QR modal');
      closeQRModal();
      showSuccess(i18next.t('whatsapp_instances.connected') || 'Connected successfully');
    }
    
    loadInstances(); // Refresh instances list
  });
  
  // Listen for WhatsApp status changes (from Evolution webhook)
  socket.on('whatsapp-status-changed', (data) => {
    console.log('WhatsApp status changed:', data);
    
    // Close QR modal if connection is established
    if (data.status === 'connected') {
      console.log('Instance connected via webhook, closing QR modal');
      closeQRModal();
      showSuccess(i18next.t('whatsapp_instances.connected') || 'Connected successfully');
    }
    
    loadInstances(); // Refresh instances list
  });
  
  // Listen for instance status changes
  socket.on('instance.status', (data) => {
    console.log('Instance status update:', data);
    
    if (data.status === 'connected' || data.status === 'open') {
      console.log('Instance connected, closing QR modal');
      closeQRModal();
      showSuccess(i18next.t('whatsapp_instances.connected') || 'Connected successfully');
    }
    
    loadInstances();
  });
  
  socket.on('disconnect', () => {
    console.log('Socket disconnected');
  });
}

/**
 * Load all instances for the tenant
 */
async function loadInstances() {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/tenant/whatsapp/instances', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error('Failed to load instances');
    }
    
    const data = await response.json();
    currentInstances = data.data.instances || [];
    
    // Store tenant limits from API response
    const limitInfo = data.data.limit || {};
    window.tenantLimits = {
      maxInstances: limitInfo.max || 1,
      currentCount: limitInfo.current || currentInstances.length,
      canCreate: limitInfo.canCreate !== undefined ? limitInfo.canCreate : true,
      remaining: limitInfo.remaining || 0
    };
    
    console.log('Loaded instances from API:', currentInstances);
    console.log('Tenant limits:', window.tenantLimits);
    
    // For each instance, check if status needs sync with Evolution API
    for (const instance of currentInstances) {
      console.log('Instance details:', {
        id: instance.id,
        name: instance.instance_name,
        status: instance.status,
        evolution_instance_id: instance.evolution_instance_id,
        hasEvolutionId: !!instance.evolution_instance_id
      });
      
      // If instance shows qr_code or connecting, verify actual status
      if (instance.status === 'qr_code' || instance.status === 'connecting') {
        if (instance.evolution_instance_id) {
          syncInstanceStatus(instance.id);
        } else {
          console.warn('Instance has no evolution_instance_id, cannot sync:', instance.id);
        }
      }
    }
    
    renderInstances();
  } catch (error) {
    console.error('Error loading instances:', error);
    showError(i18next.t('whatsapp_instances.error_loading'));
  }
}

/**
 * Sync instance status with Evolution API
 */
async function syncInstanceStatus(instanceId) {
  try {
    console.log('Syncing status for instance:', instanceId);
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/whatsapp/instances/${instanceId}/status`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const result = await response.json();
      console.log('Synced status for instance', instanceId, result.data);
      console.log('Evolution status:', result.data.evolution_status);
      console.log('Evolution instance state:', result.data.evolution_status?.instance?.state);
      
      // If status changed, reload instances
      const instance = currentInstances.find(inst => inst.id === instanceId);
      if (instance && result.data.status !== instance.status) {
        console.log('Status changed from', instance.status, 'to', result.data.status);
        // Wait a bit then reload
        setTimeout(() => loadInstances(), 500);
      } else {
        console.log('Status NOT changed. Current:', instance?.status, 'New:', result.data.status);
      }
    } else {
      console.error('Failed to sync status:', response.status, response.statusText);
    }
  } catch (error) {
    console.log('Error syncing status:', error);
  }
}

/**
 * Render instances grid
 */
function renderInstances() {
  const container = $('#instancesContainer');
  
  console.log('Rendering instances:', currentInstances);
  
  if (currentInstances.length === 0) {
    container.html(`
      <div class="empty-state">
        <i class="fab fa-whatsapp"></i>
        <h3 data-i18n="whatsapp_instances.no_instances">No instances yet</h3>
        <p data-i18n="whatsapp_instances.no_instances_desc">Create your first WhatsApp instance to get started</p>
        <button class="btn-primary" onclick="openCreateModal()">
          <i class="fas fa-plus"></i> <span data-i18n="whatsapp_instances.create_first_instance">Create First Instance</span>
        </button>
      </div>
    `);
    
    // Re-translate
    translatePage();
    return;
  }
  
  const grid = $('<div class="instances-grid"></div>');
  
  currentInstances.forEach(instance => {
    console.log('Instance status:', instance.instance_name, instance.status);
    const card = createInstanceCard(instance);
    grid.append(card);
  });
  
  container.html(grid);
  
  // Re-translate
  translatePage();
}

/**
 * Create instance card HTML
 */
function createInstanceCard(instance) {
  // Normalize status - Evolution API may return 'open' for connected
  let normalizedStatus = instance.status;
  if (normalizedStatus === 'open') {
    normalizedStatus = 'connected';
  }
  
  const statusMap = {
    'connected': 'connected',
    'open': 'connected',
    'connecting': 'connecting',
    'qr_code': 'connecting',
    'disconnected': 'disconnected',
    'close': 'disconnected'
  };
  
  const statusClass = statusMap[normalizedStatus] || 'disconnected';
  const statusTextMap = {
    'connected': 'CONNECTED',
    'open': 'CONNECTED',
    'connecting': 'CONNECTING',
    'qr_code': 'CONNECTING',
    'disconnected': 'DISCONNECTED',
    'close': 'DISCONNECTED'
  };
  const statusText = statusTextMap[normalizedStatus] || 'DISCONNECTED';
  
  const typeText = instance.instance_type === 'whatsapp_business' ? 'Official API' : 'WhatsApp Web';
  const phoneNumber = instance.phone_number || 'No number';
  
  let actions = '';
  
  // Show disconnect button if connected or open
  if (normalizedStatus === 'connected' || normalizedStatus === 'open') {
    actions = `
      <button class="btn-action btn-disconnect" onclick="disconnectInstance(${instance.id})">
        <i class="fas fa-power-off"></i> Disconnect
      </button>
      <button class="btn-action" onclick="viewInstance(${instance.id})">
        <i class="fas fa-eye"></i>
      </button>
    `;
  } else {
    // Show connect button for disconnected, connecting, or qr_code states
    actions = `
      <button class="btn-action btn-connect" onclick="connectInstance(${instance.id})">
        <i class="fas fa-qrcode"></i> Scan QR
      </button>
      <button class="btn-action btn-delete" onclick="deleteInstance(${instance.id})">
        <i class="fas fa-trash"></i>
      </button>
    `;
  }
  
  return `
    <div class="instance-card">
      <div class="instance-header">
        <div>
          <span class="status-badge status-${statusClass}">${statusText}</span>
          <span class="type-badge">${typeText}</span>
        </div>
      </div>
      <div class="instance-body">
        <div class="instance-avatar">
          ${instance.instance_name.substring(0, 2).toUpperCase()}
        </div>
        <h3 class="instance-name">${instance.instance_name}</h3>
        <p class="instance-phone">${phoneNumber}</p>
      </div>
      <div class="instance-actions">
        ${actions}
      </div>
    </div>
  `;
}

/**
 * Open create instance modal
 */
function openCreateModal() {
  // Check if limit is reached
  if (window.tenantLimits && !window.tenantLimits.canCreate) {
    showError(
      i18next.t('whatsapp_instances.limit_reached', { 
        max: window.tenantLimits.maxInstances 
      }) || `You have reached the maximum limit of ${window.tenantLimits.maxInstances} WhatsApp instance(s). Please upgrade your plan to create more instances.`
    );
    return;
  }
  
  $('#createInstanceForm')[0].reset();
  selectedInstanceType = 'whatsapp_web';
  $('.type-option').removeClass('active');
  $('.type-option[data-type="whatsapp_web"]').addClass('active');
  $('#instanceType').val('whatsapp_web');
  $('#whatsappWebFields').show();
  $('#officialApiFields').hide();
  
  $('#createInstanceModal').modal('show');
  
  setTimeout(() => {
    translatePage();
  }, 100);
}

/**
 * Close create modal
 */
function closeCreateModal() {
  // Use Bootstrap modal method
  $('#createInstanceModal').modal('hide');
}

/**
 * Select instance type
 */
function selectInstanceType(type) {
  selectedInstanceType = type;
  $('#instanceType').val(type);
  
  $('.type-option').removeClass('active');
  $(`.type-option[data-type="${type}"]`).addClass('active');
  
  if (type === 'whatsapp_business') {
    $('#whatsappWebFields').hide();
    $('#officialApiFields').show();
  } else {
    $('#whatsappWebFields').show();
    $('#officialApiFields').hide();
  }
}

/**
 * Create new instance
 */
async function createInstance() {
  const instanceName = $('#instanceName').val().trim();
  const instanceType = $('#instanceType').val();
  
  if (!instanceName) {
    showError(i18next.t('whatsapp_instances.instance_name_required'));
    return;
  }
  
  const data = {
    instance_name: instanceName,
    instance_type: instanceType
  };
  
  if (instanceType === 'whatsapp_web') {
    data.phone_number = $('#whatsappNumber').val().trim();
  }
  
  // Get the button and show loading state
  const createButton = $('#createInstanceModal').find('button.btn-primary').last();
  const originalText = createButton.html();
  
  // Get translated text or use fallback
  const creatingText = (window.i18next && window.i18next.isInitialized) 
    ? i18next.t('whatsapp_instances.creating') 
    : 'Creating...';
  
  createButton.prop('disabled', true);
  createButton.html(`<i class="fas fa-spinner fa-spin"></i> ${creatingText}`);
  
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('/api/tenant/whatsapp/instances', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    
    const result = await response.json();
    
    if (!response.ok) {
      throw new Error(result.message || 'Failed to create instance');
    }
    
    // Success - keep loading until modal closes
    showSuccess(i18next.t('whatsapp_instances.instance_created'));
    await loadInstances(); // Wait for instances to reload
    closeCreateModal(); // Then close modal
    
  } catch (error) {
    console.error('Error creating instance:', error);
    showError(error.message || i18next.t('whatsapp_instances.error_creating'));
    
    // Only restore button on error (modal stays open)
    createButton.prop('disabled', false);
    createButton.html(originalText);
  }
}

/**
 * Connect instance
 */
async function connectInstance(instanceId) {
  try {
    waitingForQR = true;
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/whatsapp/instances/${instanceId}/connect`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    const result = await response.json();
    
    if (!response.ok) {
      waitingForQR = false;
      throw new Error(result.message || 'Failed to connect instance');
    }
    
    // Don't show success alert - will show QR code modal instead
    // Show QR code if available immediately
    if (result.data && result.data.qr_code) {
      showQRCodeData(result.data.qr_code, instanceId);
    } else {
      // Poll for QR code if not available immediately
      pollForQRCode(instanceId);
    }
    
    loadInstances();
  } catch (error) {
    waitingForQR = false;
    console.error('Error connecting instance:', error);
    const errorMsg = i18next.t('whatsapp_instances.error_connecting');
    showError(error.message || (errorMsg !== 'whatsapp_instances.error_connecting' ? errorMsg : 'Error connecting instance'));
  }
}

/**
 * Poll for QR code
 */
async function pollForQRCode(instanceId, attempts = 0) {
  if (!waitingForQR || attempts >= 10) {
    if (attempts >= 10) {
      waitingForQR = false;
      console.log('Max polling attempts reached');
    }
    return;
  }
  
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`/api/tenant/whatsapp/instances/${instanceId}/qr`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      const result = await response.json();
      if (result.data && result.data.qr_code) {
        console.log('QR code received via polling');
        showQRCodeData(result.data.qr_code, instanceId);
        return;
      }
    }
  } catch (error) {
    console.log('Polling attempt failed:', error.message);
  }
  
  // Try again after 2 seconds
  setTimeout(() => pollForQRCode(instanceId, attempts + 1), 2000);
}

/**
 * Disconnect instance
 */
async function disconnectInstance(instanceId) {
  showConfirm(
    i18next.t('whatsapp_instances.disconnect_confirm'),
    async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/tenant/whatsapp/instances/${instanceId}/disconnect`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        
        if (!response.ok) {
          throw new Error(result.message || 'Failed to disconnect instance');
        }
        
        showSuccess(i18next.t('whatsapp_instances.disconnected'));
        closeQRModal();
        loadInstances();
      } catch (error) {
        console.error('Error disconnecting instance:', error);
        showError(error.message || i18next.t('whatsapp_instances.error_disconnecting'));
      }
    }
  );
}

/**
 * Delete instance
 */
async function deleteInstance(instanceId) {
  showConfirm(
    i18next.t('whatsapp_instances.delete_confirm'),
    async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/tenant/whatsapp/instances/${instanceId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        
        if (!response.ok) {
          throw new Error(result.message || 'Failed to delete instance');
        }
        
        showSuccess(i18next.t('whatsapp_instances.deleted'));
        loadInstances();
      } catch (error) {
        console.error('Error deleting instance:', error);
        showError(error.message || i18next.t('whatsapp_instances.error_deleting'));
      }
    }
  );
}

/**
 * Show QR code for instance
 */
async function showQRCode(instanceId) {
  // Instead of just fetching QR, connect the instance first
  await connectInstance(instanceId);
}

/**
 * Show QR code in modal
 */
function showQRCodeData(qrCode, instanceId) {
  // Ensure QR code has proper data URI format
  let qrCodeSrc = qrCode;
  
  // If it's just base64 without data URI prefix, add it
  if (qrCode && !qrCode.startsWith('data:')) {
    qrCodeSrc = `data:image/png;base64,${qrCode}`;
  }
  
  $('#qrCodeImage').attr('src', qrCodeSrc);
  
  // Close any alert modals before showing QR code
  $('#alertModal').modal('hide');
  
  $('#qrCodeModal').modal('show');
  
  // Start checking connection status
  if (instanceId) {
    startConnectionCheck(instanceId);
  }
}

/**
 * Start checking connection status periodically
 */
let connectionCheckInterval = null;
let lastInstanceId = null;

function startConnectionCheck(instanceId) {
  // Store the instance ID we're waiting for
  lastInstanceId = instanceId;
  
  // Clear any existing interval
  if (connectionCheckInterval) {
    clearInterval(connectionCheckInterval);
  }
  
  console.log('Starting connection check for instance:', instanceId);
  
  // Check every 2 seconds
  connectionCheckInterval = setInterval(async () => {
    if (!waitingForQR) {
      console.log('Not waiting for QR anymore, stopping check');
      clearInterval(connectionCheckInterval);
      return;
    }
    
    console.log('Checking connection status via API...');
    
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/tenant/whatsapp/instances/${instanceId}/status`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (response.ok) {
        const result = await response.json();
        const instance = result.data;
        
        console.log('Instance status from API:', instance.status, instance);
        
        // Check if connected (handle both 'connected' and 'open')
        if (instance.status === 'connected' || instance.status === 'open' || 
            (instance.evolution_status && (instance.evolution_status.state === 'open' || instance.evolution_status.instance?.state === 'open'))) {
          console.log('Instance connected! Closing modal');
          closeQRModal();
          showSuccess(i18next.t('whatsapp_instances.connected') || 'Connected successfully');
          clearInterval(connectionCheckInterval);
          loadInstances();
        }
      }
    } catch (error) {
      console.log('Error checking status:', error);
    }
  }, 2000);
}

/**
 * Close QR modal
 */
function closeQRModal() {
  waitingForQR = false;
  
  // Clear connection check interval
  if (connectionCheckInterval) {
    clearInterval(connectionCheckInterval);
    connectionCheckInterval = null;
  }
  
  $('#qrCodeModal').modal('hide');
}

/**
 * View instance details
 */
function viewInstance(instanceId) {
  // Navigate to conversations
  window.location.href = `/admin#conversations`;
}

/**
 * Utility functions
 */
function escapeHtml(text) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return text.replace(/[&<>"']/g, m => map[m]);
}

function getTenantIdFromToken() {
  const token = localStorage.getItem('token');
  if (!token) return null;
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.tenantId;
  } catch (e) {
    return null;
  }
}

function showSuccess(message) {
  $('#alertModalTitle').text('Success');
  $('#alertModalMessage').text(message);
  
  const modalHeader = $('#alertModal .modal-header');
  modalHeader.removeClass('bg-success bg-danger bg-info text-white');
  modalHeader.addClass('bg-success text-white');
  
  $('#alertModal').modal('show');
}

function showError(message) {
  $('#alertModalTitle').text('Error');
  $('#alertModalMessage').text(message);
  
  const modalHeader = $('#alertModal .modal-header');
  modalHeader.removeClass('bg-success bg-danger bg-info text-white');
  modalHeader.addClass('bg-danger text-white');
  
  $('#alertModal').modal('show');
}

function showConfirm(message, onConfirm, title = 'Confirm') {
  $('#confirmModalTitle').text(title);
  $('#confirmModalMessage').text(message);
  
  // Remove previous click handlers
  $('#confirmModalButton').off('click');
  
  // Add new click handler
  $('#confirmModalButton').on('click', function() {
    $('#confirmModal').modal('hide');
    if (onConfirm) {
      onConfirm();
    }
  });
  
  $('#confirmModal').modal('show');
}

/**
 * Sync profile pictures for all conversations
 */
async function syncProfilePictures() {
  console.log('🔄 syncProfilePictures function called');
  try {
    const token = localStorage.getItem('token');
    
    // Show loading state
    showSuccess(i18next.t('whatsapp_instances.syncing_profile_pictures') || 'Syncing profile pictures...');
    
    const response = await fetch('/api/tenant/whatsapp/sync-profile-pictures', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    const result = await response.json();
    
    if (!response.ok) {
      throw new Error(result.message || 'Failed to sync profile pictures');
    }
    
    showSuccess(result.message || i18next.t('whatsapp_instances.profile_pictures_synced') || 'Profile pictures sync started');
    
    // Reload instances after a delay to show updated pictures
    setTimeout(() => {
      loadInstances();
    }, 3000);
    
  } catch (error) {
    console.error('Error syncing profile pictures:', error);
    showError(error.message || i18next.t('whatsapp_instances.error_syncing_profile_pictures') || 'Error syncing profile pictures');
  }
}

// Verify function is available globally
console.log('✅ syncProfilePictures function defined:', typeof syncProfilePictures);
window.syncProfilePictures = syncProfilePictures; // Ensure it's globally available

// Bootstrap modals handle backdrop clicks automatically, so we don't need this
