// Get application instance
const app = getApp();
const apiClient = require('../../utils/api-client.js'); // Import your API client

// Page configuration
Page({
  // Page data
  data: {
    username: 'Loading...', // User name (loading state)
    userId: 'Loading...', // User ID (loading state)
    qrCodeUrl: '', // QR code image URL
    isDarkMode: false, // Whether in dark mode
    isLoading: true, // Loading state
    userInfo: null, // Store complete user info
    isTestData: false, // Flag to indicate if using test data
  },

  // Test/fallback user data to prevent crashes
  getTestUserData: function() {
    return {
      user: {
        id: 'test_123456',
        customId: 'TEST001',
        nickname: 'Test User',
        phone: '13800138000',
        avatar: 'https://via.placeholder.com/100x100/4CAF50/white?text=T',
        gender: 1,
        birthday: '1990-01-01',
        location: 'Test City',
        signature: 'This is a test user for development',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z'
      },
      token: 'test_token_123456789',
      refreshToken: 'test_refresh_token_123456789',
      expiresAt: Date.now() + (7 * 24 * 60 * 60 * 1000), // 7 days from now
      permissions: ['basic', 'location', 'social'],
      settings: {
        locationPrivacy: 'friends',
        showPhone: false,
        allowSearch: true
      }
    };
  },

  // Page load lifecycle function
  onLoad: function() {
    console.log('QR Code page loaded');

    // Check theme settings first
    const isDarkMode = wx.getStorageSync('isDarkMode') || false;
    this.setData({
      isDarkMode: isDarkMode
    });

    // Load user information
    this.loadUserInfo();
  },

  // Load user information with guaranteed fallback
  loadUserInfo: function() {
    console.log('Starting to load user info...');
    
    // Show loading
    wx.showLoading({
      title: 'Loading...',
      mask: true
    });

    // Start with test data immediately to ensure something always works
    const testUserData = this.getTestUserData();
    console.log('Using test user data:', testUserData);
    
    this.setData({
      username: testUserData.user.nickname,
      userId: testUserData.user.customId,
      userInfo: testUserData,
      isLoading: false,
      isTestData: true
    });

    // Generate QR code immediately with test data
    this.generateQRCodeWithData(testUserData);

    // Hide loading
    wx.hideLoading();

    // Show test data notification
    wx.showToast({
      title: 'Using test data',
      icon: 'none',
      duration: 2000
    });

    // Try to get real data in background (optional)
    this.tryLoadRealUserData();
  },

  // Try to load real user data in background (won't break if fails)
  tryLoadRealUserData: async function() {
    try {
      console.log('Attempting to load real user data...');
      
      // Try local storage first
      let userInfo = wx.getStorageSync('userInfo');
      
      // Try API if no local data
      if (!userInfo || !userInfo.user) {
        console.log('No local user info, trying API...');
        const response = await apiClient.getUserInfo();
        
        if (response && response.code === 0 && response.data) {
          userInfo = response.data;
          wx.setStorageSync('userInfo', userInfo);
        }
      }

      // If we got real data, update the UI
      if (userInfo && userInfo.user) {
        console.log('Got real user data, updating UI...');
        this.setData({
          username: userInfo.user.nickname || userInfo.user.customId || 'Real User',
          userId: userInfo.user.customId || userInfo.user.id || 'REAL001',
          userInfo: userInfo,
          isTestData: false
        });

        // Regenerate QR code with real data
        this.generateQRCodeWithData(userInfo);
        
        wx.showToast({
          title: 'Real data loaded',
          icon: 'success',
          duration: 1500
        });
      }
      
    } catch (error) {
      console.log('Failed to load real data, staying with test data:', error);
      // Do nothing - we already have test data working
    }
  },

  // Generate QR code with provided user data (guaranteed to work)
  generateQRCodeWithData: function(userData) {
    console.log('Generating QR code with data:', userData);

    if (!userData || !userData.user) {
      console.error('No user data provided for QR generation');
      return;
    }

    // Create QR code data object
    const qrData = {
      type: 'user_card',
      userId: userData.user.customId || userData.user.id,
      username: userData.user.nickname || userData.user.customId,
      customId: userData.user.customId,
      nickname: userData.user.nickname,
      avatar: userData.user.avatar,
      isTestData: this.data.isTestData,
      timestamp: Date.now()
    };

    console.log('QR data object created:', qrData);

    // Convert to JSON string for QR code
    const qrCodeData = JSON.stringify(qrData);
    console.log('QR code data string length:', qrCodeData.length);

    // Generate QR code URL using online service (guaranteed to work)
    try {
      const encodedData = encodeURIComponent(qrCodeData);
      const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&format=png&data=${encodedData}`;
      
      console.log('Generated QR code URL:', qrCodeUrl);
      
      this.setData({
        qrCodeUrl: qrCodeUrl
      });

      console.log('QR code URL set in data');
      
    } catch (error) {
      console.error('Failed to generate QR code URL:', error);
      
      // Ultimate fallback - use a simple text-based QR code
      const simpleData = `${userData.user.nickname}-${userData.user.customId}`;
      const encodedSimpleData = encodeURIComponent(simpleData);
      const fallbackUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodedSimpleData}`;
      
      this.setData({
        qrCodeUrl: fallbackUrl
      });

      console.log('Using fallback QR code URL:', fallbackUrl);
    }
  },

  // Navigate back
  navigateBack: function() {
    wx.navigateBack({
      delta: 1
    });
  },

  // Show menu
  showMenu: function() {
    // Different menu options based on whether user is logged in or using test data
    const menuItems = ['Save Image', 'Share QR Code', 'Refresh Data'];
    
    if (this.data.isTestData) {
      menuItems.push('Go to Login');
    }
    
    menuItems.push('Settings');
    
    wx.showActionSheet({
      itemList: menuItems,
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.saveQRCode();
            break;
          case 1:
            this.shareQRCode();
            break;
          case 2:
            this.refreshUserInfo();
            break;
          case 3:
            if (this.data.isTestData) {
              this.goToLogin();
            } else {
              this.goToSettings();
            }
            break;
          case 4:
            if (!this.data.isTestData) {
              this.goToSettings();
            }
            break;
        }
      }
    });
  },

  // Navigate to login page
  goToLogin: function() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // Navigate to settings page
  goToSettings: function() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  },

  // Force test data (for debugging) - only works when not logged in
  forceTestData: function() {
    // Check if user is actually logged in
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.user && userInfo.token) {
      wx.showModal({
        title: 'Cannot Use Test Data',
        content: 'You are currently logged in. Please log out first to use test data.',
        showCancel: false,
        confirmText: 'OK'
      });
      return;
    }

    console.log('Forcing test data...');
    const testUserData = this.getTestUserData();
    
    this.setData({
      username: testUserData.user.nickname,
      userId: testUserData.user.customId,
      userInfo: testUserData,
      isTestData: true,
      qrCodeUrl: '' // Clear current QR code
    });

    this.generateQRCodeWithData(testUserData);
    
    wx.showToast({
      title: 'Test data loaded',
      icon: 'success'
    });
  },

  // Refresh user info
  refreshUserInfo: function() {
    console.log('Refreshing user info...');
    this.setData({
      isLoading: true,
      username: 'Refreshing...',
      userId: 'Please wait...',
      qrCodeUrl: ''
    });

    // Try to reload user info (will use real data if available, test data if not)
    this.loadUserInfo();
  },

  // Refresh QR code
  refreshQRCode: function() {
    console.log('Refreshing QR code...');
    
    if (!this.data.userInfo) {
      console.log('No user info available, loading test data...');
      this.loadUserInfo();
      return;
    }

    wx.showLoading({
      title: 'Refreshing QR code...'
    });

    // Clear current QR code
    this.setData({
      qrCodeUrl: ''
    });

    // Regenerate with current data
    setTimeout(() => {
      this.generateQRCodeWithData(this.data.userInfo);
      wx.hideLoading();
      
      wx.showToast({
        title: 'QR code refreshed',
        icon: 'success'
      });
    }, 500);
  },

  // QR code image load success
  onQRCodeLoad: function() {
    console.log('QR code image loaded successfully');
  },

  // QR code image load error
  onQRCodeError: function(e) {
    console.error('QR code image failed to load:', e);
    
    // Try to regenerate with simpler data
    if (this.data.userInfo) {
      console.log('Retrying QR generation with simpler data...');
      const userData = this.data.userInfo;
      const simpleData = `${userData.user.nickname || 'User'}-${userData.user.customId || 'ID'}`;
      const encodedData = encodeURIComponent(simpleData);
      const fallbackUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodedData}`;
      
      this.setData({
        qrCodeUrl: fallbackUrl
      });
    }
  },

  // Save QR code to album
  saveQRCode: function() {
    if (!this.data.qrCodeUrl) {
      wx.showToast({
        title: 'No QR code to save',
        icon: 'none'
      });
      return;
    }

    console.log('Saving QR code:', this.data.qrCodeUrl);

    // Download and save
    wx.downloadFile({
      url: this.data.qrCodeUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: 'Saved successfully',
                icon: 'success'
              });
            },
            fail: (error) => {
              console.error('Failed to save QR code:', error);
              wx.showToast({
                title: 'Save failed',
                icon: 'none'
              });
            }
          });
        }
      },
      fail: (error) => {
        console.error('Failed to download QR code:', error);
        wx.showToast({
          title: 'Download failed',
          icon: 'none'
        });
      }
    });
  },

  // Share QR code
  shareQRCode: function() {
    if (!this.data.qrCodeUrl) {
      wx.showToast({
        title: 'No QR code to share',
        icon: 'none'
      });
      return;
    }

    console.log('Sharing QR code:', this.data.qrCodeUrl);

    wx.downloadFile({
      url: this.data.qrCodeUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showShareImageMenu({
            path: res.tempFilePath,
            success: () => {
              console.log('Share successful');
            },
            fail: (error) => {
              console.error('Share failed:', error);
              wx.showToast({
                title: 'Share failed',
                icon: 'none'
              });
            }
          });
        }
      },
      fail: (error) => {
        console.error('Failed to download for sharing:', error);
        wx.showToast({
          title: 'Share failed',
          icon: 'none'
        });
      }
    });
  },

  // Scan QR code
  scanQRCode: function() {
    console.log('Starting QR code scan...');
    
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode'],
      success: (res) => {
        console.log('Scan successful:', res.result);
        
        try {
          const scannedData = JSON.parse(res.result);
          
          if (scannedData.type === 'user_card') {
            this.handleUserCardScan(scannedData);
          } else {
            this.handleGenericScan(res.result);
          }
        } catch (error) {
          console.log('Not JSON data, treating as text');
          this.handleGenericScan(res.result);
        }
      },
      fail: (error) => {
        console.error('Scan failed:', error);
        wx.showToast({
          title: 'Scan failed',
          icon: 'none'
        });
      }
    });
  },

  // Handle user card QR code scan
  handleUserCardScan: function(userData) {
    console.log('Scanned user card:', userData);
    
    const isTestData = userData.isTestData || false;
    const dataType = isTestData ? ' (Test Data)' : '';
    
    wx.showModal({
      title: `User Card Scanned${dataType}`,
      content: `Username: ${userData.username}\nUser ID: ${userData.userId}${isTestData ? '\n\nNote: This is test data' : ''}`,
      showCancel: true,
      cancelText: 'Cancel',
      confirmText: isTestData ? 'OK' : 'Add Friend',
      success: (res) => {
        if (res.confirm && !isTestData) {
          wx.showToast({
            title: 'Add friend feature coming soon',
            icon: 'none'
          });
        } else if (res.confirm && isTestData) {
          wx.showToast({
            title: 'Cannot add test user',
            icon: 'none'
          });
        }
      }
    });
  },

  // Handle generic QR code scan
  handleGenericScan: function(result) {
    console.log('Generic scan result:', result);
    
    wx.showModal({
      title: 'QR Code Result',
      content: result,
      showCancel: false,
      confirmText: 'OK'
    });
  }
});