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

class WhatsAppInstancesManager {
  constructor() {
    this.instances = [];
    this.limit = { current: 0, max: 1, remaining: 1 };
    this.socket = null;
    this.currentQRInstance = null;
    this.qrCheckInterval = null;
    
    this.init();
  }

  async init() {
    await this.loadInstances();
    this.setupSocketIO();
    this.setupEventListeners();
  }

  /**
   * Setup Socket.IO for real-time updates
   */
  setupSocketIO() {
    const tenantId = this.getTenantId();
    if (!tenantId) return;

    this.socket = io(`/tenant/${tenantId}`, {
      transports: ['websocket', 'polling']
    });

    this.socket.on('connect', () => {
      console.log('Connected to WhatsApp instances socket');
    });

    this.socket.on('whatsapp-qr-updated', (data) => {
      console.log('🔔 QR code updated event received', data);
      this.handleQRUpdate(data);
    });

    this.socket.on('whatsapp-status-changed', (data) => {
      console.log('🔔 Status changed event received', data);
      this.handleStatusChange(data);
    });

    this.socket.on('disconnect', () => {
      console.log('Disconnected from WhatsApp instances socket');
    });
  }

  /**
   * Get tenant ID from token
   */
  getTenantId() {
    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;
    }
  }

  /**
   * Setup event listeners
   */
  setupEventListeners() {
    // Add connection button
    const addBtn = document.getElementById('add-whatsapp-connection');
    if (addBtn) {
      addBtn.addEventListener('click', () => this.showCreateModal());
    }

    // Modal close buttons
    const closeButtons = document.querySelectorAll('[data-dismiss="modal"]');
    closeButtons.forEach(btn => {
      btn.addEventListener('click', (e) => {
        const modal = e.target.closest('.modal');
        if (modal) {
          this.closeModal(modal.id);
        }
      });
    });

    // Create instance form
    const createForm = document.getElementById('create-instance-form');
    if (createForm) {
      createForm.addEventListener('submit', (e) => {
        e.preventDefault();
        this.createInstance();
      });
    }
  }

  /**
   * Load instances from API
   */
  async loadInstances() {
    try {
      const response = await this.apiCall('/api/tenant/whatsapp/instances', 'GET');
      
      if (response.success) {
        this.instances = response.data.instances || [];
        this.limit = response.data.limit || { current: 0, max: 1, remaining: 1 };
        this.renderInstances();
      }
    } catch (error) {
      console.error('Error loading instances:', error);
      this.showError(this.t('whatsapp.instances.errors.load_failed'));
    }
  }

  /**
   * Render instances list
   */
  renderInstances() {
    const container = document.getElementById('whatsapp-instances-list');
    if (!container) return;

    if (this.instances.length === 0) {
      container.innerHTML = `
        <div class="text-center py-5">
          <i class="fas fa-whatsapp fa-3x text-muted mb-3"></i>
          <p class="text-muted" data-i18n="whatsapp.instances.no_instances">No instances configured</p>
          <button class="btn btn-primary" onclick="whatsappManager.showCreateModal()">
            <i class="fas fa-plus"></i> <span data-i18n="whatsapp.instances.add_connection">Add Connection</span>
          </button>
        </div>
      `;
      return;
    }

    container.innerHTML = this.instances.map(instance => this.renderInstanceCard(instance)).join('');
  }

  /**
   * Render single instance card
   */
  renderInstanceCard(instance) {
    const statusClass = {
      'connected': 'success',
      'connecting': 'warning',
      'qr_code': 'info',
      'disconnected': 'secondary',
      'error': 'danger'
    }[instance.status] || 'secondary';

    const statusText = this.t(`whatsapp.instances.status.${instance.status}`) || instance.status.toUpperCase();

    // Get initials for avatar fallback
    const initials = instance.instance_name
      .split(' ')
      .map(word => word[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);

    // Profile picture or avatar
    const avatarHtml = instance.profile_picture_url 
      ? `<img src="${this.escapeHtml(instance.profile_picture_url)}" alt="${this.escapeHtml(instance.instance_name)}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 50%;">` 
      : `<span style="font-size: 32px; font-weight: 600;">${initials}</span>`;

    return `
      <div class="col-md-4 mb-3" data-instance-id="${instance.id}">
        <div class="card">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-3">
              <div>
                <h5 class="card-title mb-1">${this.escapeHtml(instance.instance_name)}</h5>
                <small class="text-muted">
                  ${instance.phone_number || '<span data-i18n="whatsapp.instances.no_number">No number</span>'}
                </small>
              </div>
              <span class="badge badge-${statusClass}">${statusText}</span>
            </div>
            
            <div class="text-center mb-3">
              <div class="instance-avatar" style="width: 80px; height: 80px; margin: 0 auto; border-radius: 50%; background: linear-gradient(135deg, #25d366 0%, #128c7e 100%); color: white; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                ${avatarHtml}
              </div>
              ${instance.profile_name ? `<p class="mt-2 mb-0 text-muted" style="font-size: 13px;">${this.escapeHtml(instance.profile_name)}</p>` : ''}
            </div>
            
            <div class="mb-3">
              <span class="badge badge-light">
                <i class="fas fa-${instance.instance_type === 'whatsapp_business' ? 'building' : 'globe'}"></i>
                ${instance.instance_type === 'whatsapp_business' ? 'WABA' : 'WhatsApp Web'}
              </span>
            </div>

            <div class="btn-group btn-group-sm w-100" role="group">
              ${instance.status === 'disconnected' || instance.status === 'error' ? `
                <button class="btn btn-success" onclick="whatsappManager.connectInstance(${instance.id})">
                  <i class="fas fa-plug"></i> <span data-i18n="whatsapp.instances.actions.connect">Connect</span>
                </button>
              ` : ''}
              
              ${instance.status === 'qr_code' || instance.status === 'connecting' ? `
                <button class="btn btn-info" onclick="whatsappManager.showQRCode(${instance.id})">
                  <i class="fas fa-qrcode"></i> <span data-i18n="whatsapp.instances.actions.read_qr">Read QR</span>
                </button>
              ` : ''}
              
              ${instance.status === 'connected' ? `
                <button class="btn btn-warning" onclick="whatsappManager.disconnectInstance(${instance.id})">
                  <i class="fas fa-unlink"></i> <span data-i18n="whatsapp.instances.actions.disconnect">Disconnect</span>
                </button>
              ` : ''}
              
              <button class="btn btn-info" onclick="whatsappManager.showEditModal(${instance.id})">
                <i class="fas fa-cog"></i> <span data-i18n="whatsapp.instances.actions.settings">Settings</span>
              </button>
              
              <button class="btn btn-danger" onclick="whatsappManager.deleteInstance(${instance.id})">
                <i class="fas fa-trash"></i> <span data-i18n="whatsapp.instances.actions.delete">Delete</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    `;
  }

  /**
   * Show create instance modal
   */
  showCreateModal() {
    if (this.limit.remaining <= 0) {
      this.showError(this.t('whatsapp.instances.limit_reached'));
      return;
    }

    // Reset form
    document.getElementById('createInstanceForm').reset();
    
    // Show modal
    $('#createInstanceModal').modal('show');
  }

  /**
   * Show edit instance modal
   */
  async showEditModal(instanceId) {
    const instance = this.instances.find(i => i.id === instanceId);
    if (!instance) return;

    // Populate form with instance data
    document.getElementById('instanceName').value = instance.instance_name;
    document.getElementById('whatsappNumber').value = instance.phone_number || '';

    // Load settings from Evolution API
    try {
      const response = await this.apiCall(`/api/tenant/whatsapp/instances/${instanceId}/settings`, 'GET');
      
      if (response.success && response.data) {
        const settings = response.data;
        
        // Set toggle switches
        document.getElementById('rejectCalls').checked = settings.rejectCall || false;
        document.getElementById('alwaysOnline').checked = settings.alwaysOnline || false;
        document.getElementById('readMessages').checked = settings.readMessages || false;
        document.getElementById('readStatus').checked = settings.readStatus || false;
        document.getElementById('syncFullHistory').checked = settings.syncFullHistory || false;
        document.getElementById('groupsIgnore').checked = settings.groupsIgnore || false;
      }
    } catch (error) {
      console.error('Error loading settings:', error);
      // Use connection_data from database as fallback
      if (instance.connection_data) {
        document.getElementById('rejectCalls').checked = instance.connection_data.rejectCall || false;
        document.getElementById('alwaysOnline').checked = instance.connection_data.alwaysOnline || false;
        document.getElementById('readMessages').checked = instance.connection_data.readMessages || false;
        document.getElementById('readStatus').checked = instance.connection_data.readStatus || false;
        document.getElementById('syncFullHistory').checked = instance.connection_data.syncFullHistory || false;
        document.getElementById('groupsIgnore').checked = instance.connection_data.groupsIgnore || false;
      }
    }

    // Change modal title and button
    document.querySelector('#createInstanceModal .modal-title').textContent = 'Edit Instance Settings';
    const submitBtn = document.querySelector('#createInstanceModal .btn-primary');
    submitBtn.textContent = 'Update Settings';
    submitBtn.onclick = () => this.updateInstanceSettings(instanceId);

    // Show modal
    $('#createInstanceModal').modal('show');
  }

  /**
   * Update instance settings
   */
  async updateInstanceSettings(instanceId) {
    const settings = {
      rejectCall: document.getElementById('rejectCalls').checked,
      alwaysOnline: document.getElementById('alwaysOnline').checked,
      readMessages: document.getElementById('readMessages').checked,
      readStatus: document.getElementById('readStatus').checked,
      syncFullHistory: document.getElementById('syncFullHistory').checked,
      groupsIgnore: document.getElementById('groupsIgnore').checked
    };

    try {
      const submitBtn = document.querySelector('#createInstanceModal .btn-primary');
      if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
      }

      const response = await this.apiCall(`/api/tenant/whatsapp/instances/${instanceId}/settings`, 'PUT', settings);

      if (response.success) {
        this.showSuccess('Settings updated successfully');
        $('#createInstanceModal').modal('hide');
        await this.loadInstances();
      } else {
        this.showError(response.message || 'Failed to update settings');
      }
    } catch (error) {
      console.error('Error updating settings:', error);
      this.showError(error.message || 'Failed to update settings');
    } finally {
      const submitBtn = document.querySelector('#createInstanceModal .btn-primary');
      if (submitBtn) {
        submitBtn.disabled = false;
        submitBtn.innerHTML = 'Update Settings';
      }
    }
  }

  /**
   * Create new instance
   */
  async createInstance() {
    const instanceName = document.getElementById('instanceName').value;
    const whatsappNumber = document.getElementById('whatsappNumber').value;
    
    const data = {
      instance_name: instanceName,
      instance_type: 'whatsapp_web',
      phone_number: whatsappNumber
    };

    console.log('Creating instance with data:', data);

    if (!data.instance_name) {
      this.showError(this.t('whatsapp.instances.errors.name_required') || 'Instance name is required');
      return;
    }

    try {
      const submitBtn = document.querySelector('#createInstanceModal .btn-primary');
      const cancelBtn = document.querySelector('#createInstanceModal .btn-secondary');
      
      if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>' + (this.t('whatsapp_instances.creating_instance') || 'Creating instance...');
      }
      
      if (cancelBtn) {
        cancelBtn.disabled = true;
      }

      console.log('Calling API...');
      const response = await this.apiCall('/api/tenant/whatsapp/instances', 'POST', data);
      console.log('API response:', response);

      if (response.success) {
        this.showSuccess(this.t('whatsapp_instances.instance_created') || 'Instance created successfully!');
        $('#createInstanceModal').modal('hide');
        document.getElementById('createInstanceForm').reset();
        await this.loadInstances();
        
        // Auto-connect the new instance
        if (response.data && response.data.id) {
          setTimeout(() => {
            this.connectInstance(response.data.id);
          }, 1000);
        }
      } else {
        this.showError(response.message || this.t('whatsapp.instances.errors.create_failed') || 'Failed to create instance');
      }
    } catch (error) {
      console.error('Error creating instance:', error);
      this.showError(error.message || this.t('whatsapp.instances.errors.create_failed') || 'Failed to create instance');
    } finally {
      const submitBtn = document.querySelector('#createInstanceModal .btn-primary');
      const cancelBtn = document.querySelector('#createInstanceModal .btn-secondary');
      
      if (submitBtn) {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-plus mr-2"></i>' + (this.t('whatsapp_instances.create_instance') || 'Create Instance');
      }
      
      if (cancelBtn) {
        cancelBtn.disabled = false;
      }
    }
  }

  /**
   * Connect instance
   */
  async connectInstance(instanceId) {
    try {
      const response = await this.apiCall(`/api/tenant/whatsapp/instances/${instanceId}/connect`, 'POST');

      if (response.success) {
        this.showSuccess(this.t('whatsapp.instances.success.connected'));
        await this.loadInstances();
        
        // Show QR code if available
        if (response.data && response.data.qr_code) {
          this.currentQRInstance = instanceId;
          this.displayQRCode(response.data.qr_code);
          this.showQRModal();
          this.startQRPolling(instanceId);
        } else if (response.data && response.data.status === 'connecting') {
          // Start polling for QR code
          this.currentQRInstance = instanceId;
          this.showQRModal();
          this.startQRPolling(instanceId);
        }
      } else {
        this.showError(response.message || this.t('whatsapp.instances.errors.connect_failed'));
      }
    } catch (error) {
      console.error('Error connecting instance:', error);
      this.showError(this.t('whatsapp.instances.errors.connect_failed'));
    }
  }

  /**
   * Disconnect instance
   */
  async disconnectInstance(instanceId) {
    if (!confirm(this.t('whatsapp.instances.confirm_disconnect') || 'Are you sure you want to disconnect this instance?')) {
      return;
    }

    try {
      const response = await this.apiCall(`/api/tenant/whatsapp/instances/${instanceId}/disconnect`, 'POST');

      if (response.success) {
        this.showSuccess(this.t('whatsapp.instances.success.disconnected'));
        await this.loadInstances();
      } else {
        this.showError(response.message || this.t('whatsapp.instances.errors.disconnect_failed'));
      }
    } catch (error) {
      console.error('Error disconnecting instance:', error);
      this.showError(this.t('whatsapp.instances.errors.disconnect_failed'));
    }
  }

  /**
   * Delete instance
   */
  async deleteInstance(instanceId) {
    if (!confirm(this.t('whatsapp.instances.confirm_delete'))) {
      return;
    }

    try {
      const response = await this.apiCall(`/api/tenant/whatsapp/instances/${instanceId}`, 'DELETE');

      if (response.success) {
        this.showSuccess(this.t('whatsapp.instances.success.deleted'));
        await this.loadInstances();
      } else {
        this.showError(response.message || this.t('whatsapp.instances.errors.delete_failed'));
      }
    } catch (error) {
      console.error('Error deleting instance:', error);
      this.showError(this.t('whatsapp.instances.errors.delete_failed'));
    }
  }

  /**
   * Show QR code for instance
   */
  async showQRCode(instanceId) {
    this.currentQRInstance = instanceId;
    this.showQRModal();
    this.startQRPolling(instanceId);
  }

  /**
   * Start polling for QR code updates
   */
  startQRPolling(instanceId) {
    this.stopQRPolling();
    
    this.qrCheckInterval = setInterval(async () => {
      try {
        const response = await this.apiCall(`/api/tenant/whatsapp/instances/${instanceId}/qr`, 'GET');
        
        if (response.success && response.data && response.data.qr_code) {
          this.displayQRCode(response.data.qr_code);
        }
      } catch (error) {
        console.error('Error polling QR code:', error);
      }
    }, 3000);
  }

  /**
   * Stop QR code polling
   */
  stopQRPolling() {
    if (this.qrCheckInterval) {
      clearInterval(this.qrCheckInterval);
      this.qrCheckInterval = null;
    }
  }

  /**
   * Display QR code in modal
   */
  displayQRCode(qrCode) {
    const container = document.getElementById('qr-code-display');
    if (!container) return;

    // Clear loading state
    container.innerHTML = '';

    // Display QR code
    if (qrCode.startsWith('data:image')) {
      container.innerHTML = `<img src="${qrCode}" alt="QR Code" class="img-fluid" style="max-width: 300px;">`;
    } else {
      // Generate QR code from text
      container.innerHTML = '<div id="qrcode"></div>';
      new QRCode(document.getElementById('qrcode'), {
        text: qrCode,
        width: 300,
        height: 300
      });
    }
  }

  /**
   * Show QR modal
   */
  showQRModal() {
    const modal = document.getElementById('qr-code-modal');
    if (modal) {
      const container = document.getElementById('qr-code-display');
      if (container) {
        container.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin fa-3x"></i><p class="mt-3">Loading QR Code...</p></div>';
      }
      modal.style.display = 'flex';
    }
  }

  /**
   * Close modal
   */
  closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
      modal.style.display = 'none';
      
      // Also try with Bootstrap modal if available
      if (typeof $ !== 'undefined' && $.fn.modal) {
        $(`#${modalId}`).modal('hide');
      }
      
      if (modalId === 'qrCodeModal' || modalId === 'qr-code-modal') {
        this.stopQRPolling();
        this.currentQRInstance = null;
      }
    }
  }

  /**
   * Handle QR code update from socket
   */
  handleQRUpdate(data) {
    if (data.instanceId === this.currentQRInstance && data.qrCode) {
      this.displayQRCode(data.qrCode);
    }
    
    // Update instance status
    this.updateInstanceStatus(data.instanceId, 'qr_code');
  }

  /**
   * Handle status change from socket
   */
  handleStatusChange(data) {
    console.log('📱 Handling status change:', data);
    
    this.updateInstanceStatus(data.instanceId, data.status, data.phoneNumber, data.profilePictureUrl, data.profileName);
    
    // If connected, close QR modal and stop polling
    if (data.status === 'connected') {
      console.log('✅ Instance connected!', data);
      
      if (data.instanceId === this.currentQRInstance) {
        console.log('🔒 Closing QR modal and stopping polling');
        
        // Stop polling
        if (this.qrCheckInterval) {
          clearInterval(this.qrCheckInterval);
          this.qrCheckInterval = null;
        }
        
        // Close modal
        this.closeModal('qrCodeModal');
        
        // Show success message
        const phoneDisplay = data.phoneNumber || 'Unknown';
        this.showSuccess(`Connected successfully! Phone: ${phoneDisplay}`);
        
        // Reset current QR instance
        this.currentQRInstance = null;
      }
      
      // Reload instances to get updated data including profile picture
      this.loadInstances();
    }
  }

  /**
   * Update instance status in UI
   */
  updateInstanceStatus(instanceId, status, phoneNumber, profilePictureUrl, profileName) {
    const instance = this.instances.find(i => i.id === instanceId);
    if (instance) {
      instance.status = status;
      if (phoneNumber) {
        instance.phone_number = phoneNumber;
      }
      if (profilePictureUrl) {
        instance.profile_picture_url = profilePictureUrl;
      }
      if (profileName) {
        instance.profile_name = profileName;
      }
      this.renderInstances();
    }
  }

  /**
   * API call helper
   */
  async apiCall(url, method = 'GET', data = null) {
    const token = localStorage.getItem('token');
    const options = {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    };

    if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
      options.body = JSON.stringify(data);
    }

    const response = await fetch(url, options);
    return await response.json();
  }

  /**
   * Translation helper
   */
  t(key) {
    // Use i18next if available
    if (window.i18next) {
      return window.i18next.t(key);
    }
    return key;
  }

  /**
   * Show success message
   */
  showSuccess(message) {
    console.log('Success:', 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');
  }

  /**
   * Show error message
   */
  showError(message) {
    console.error('Error:', 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');
  }

  /**
   * Escape HTML
   */
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  /**
   * Sync profile pictures for all conversations
   */
  async syncProfilePictures() {
    try {
      this.showSuccess(this.t('whatsapp_instances.syncing_profile_pictures') || 'Syncing profile pictures...');
      
      const result = await this.apiCall('/api/tenant/whatsapp/sync-profile-pictures', 'POST');
      
      if (result.success) {
        this.showSuccess(result.message || this.t('whatsapp_instances.profile_pictures_synced') || 'Profile pictures sync started successfully');
        
        // Reload instances after a delay to show updated pictures
        setTimeout(() => {
          this.loadInstances();
        }, 3000);
      } else {
        throw new Error(result.message || 'Failed to sync profile pictures');
      }
    } catch (error) {
      console.error('Error syncing profile pictures:', error);
      this.showError(error.message || this.t('whatsapp_instances.error_syncing_profile_pictures') || 'Error syncing profile pictures');
    }
  }
}

// Initialize when DOM is ready
let whatsappManager;
document.addEventListener('DOMContentLoaded', () => {
  whatsappManager = new WhatsAppInstancesManager();
});


// Helper function to close modal
function closeEvolutionModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.style.display = 'none';
    
    if (modalId === 'qr-code-modal' && window.whatsappManager) {
      window.whatsappManager.stopQRPolling();
      window.whatsappManager.currentQRInstance = null;
    }
  }
}

// Global functions for HTML onclick handlers
function openCreateModal() {
  $('#createInstanceModal').modal('show');
}

function createInstance() {
  if (window.whatsappManager) {
    window.whatsappManager.createInstance();
  }
}

function connectInstance(instanceId) {
  if (window.whatsappManager) {
    window.whatsappManager.connectInstance(instanceId);
  }
}

function disconnectInstance(instanceId) {
  if (window.whatsappManager) {
    window.whatsappManager.disconnectInstance(instanceId);
  }
}

function deleteInstance(instanceId) {
  if (window.whatsappManager) {
    window.whatsappManager.deleteInstance(instanceId);
  }
}

function showQRCode(instanceId) {
  if (window.whatsappManager) {
    window.whatsappManager.showQRCode(instanceId);
  }
}

function syncProfilePictures() {
  if (window.whatsappManager) {
    window.whatsappManager.syncProfilePictures();
  }
}

// Close modal when clicking outside
window.addEventListener('click', (e) => {
  if (e.target.classList.contains('modal')) {
    e.target.style.display = 'none';
  }
});

// Export manager globally
window.whatsappManager = whatsappManager;
