import { sendOrderSuccessEmail, sendAccountDeliveryEmail, sendPaymentSuccessEmail } from './email'

const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN
const TELEGRAM_ADMIN_CHAT_ID = process.env.TELEGRAM_ADMIN_CHAT_ID

// ============================================
// WA NOTIFICATION (Implement your provider)
// ============================================
export async function sendWaNotification(phone: string, message: string) {
  if (!phone) return
  console.log(`[WA Notification to ${phone}] ${message}`)
  // TODO: Implement WA Provider API (Fonnte, Wablas, dll) here
  // const res = await fetch('https://api.fonnte.com/send', {
  //   method: 'POST',
  //   headers: { 'Authorization': process.env.WA_API_TOKEN! },
  //   body: JSON.stringify({ target: phone, message })
  // })
}

// ============================================
// TELEGRAM NOTIFICATION (User)
// ============================================
export async function sendTelegramNotification(telegramId: string, message: string) {
  if (!telegramId || !TELEGRAM_BOT_TOKEN) return
  try {
    await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: telegramId, text: message, parse_mode: 'HTML' })
    })
  } catch (error) {
    console.error('Failed to send Telegram notification:', error)
  }
}

// ============================================
// TELEGRAM ADMIN NOTIFICATION
// ============================================
export async function notifyAdmin(message: string) {
  if (!TELEGRAM_ADMIN_CHAT_ID || !TELEGRAM_BOT_TOKEN) return
  try {
    await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: TELEGRAM_ADMIN_CHAT_ID, text: message, parse_mode: 'HTML' })
    })
  } catch (error) {
    console.error('Failed to send admin Telegram notification:', error)
  }
}

// ============================================
// ORDER SUCCESS (+ Admin notif for MANUAL)
// ============================================
export async function notifyOrderSuccess(user: any, orderData: {
  name: string
  orderId: string
  productName: string
  targetId?: string
  zone?: string
  price: number
  isManual?: boolean
}) {
  // 1. Email to user
  if (user.email) {
    await sendOrderSuccessEmail(user.email, orderData).catch(console.error)
  }

  const userMsg = `✅ <b>Pesanan Berhasil!</b>\n\nHi ${orderData.name},\nPesanan kamu telah berhasil diproses!\n\nOrder ID: #${orderData.orderId.slice(-8).toUpperCase()}\nProduk: ${orderData.productName}\n${orderData.targetId ? `Tujuan: ${orderData.targetId}${orderData.zone ? ` (${orderData.zone})` : ''}\n` : ''}Total: Rp ${orderData.price.toLocaleString('id-ID')}`

  // 2. WA to user
  if (user.whatsappNumber) {
    await sendWaNotification(user.whatsappNumber, userMsg).catch(console.error)
  }

  // 3. Telegram to user
  if (user.telegramId) {
    await sendTelegramNotification(user.telegramId, userMsg).catch(console.error)
  }

  // 4. If MANUAL delivery, notify admin to process it
  if (orderData.isManual) {
    const adminMsg = `🛎️ <b>Order MANUAL Baru!</b>\n\n📦 Produk: ${orderData.productName}\n👤 Customer: ${orderData.name} (${user.email})\nOrder ID: #${orderData.orderId.slice(-8).toUpperCase()}\n💰 Total: Rp ${orderData.price.toLocaleString('id-ID')}\n\n<i>Segera proses pesanan ini melalui Admin Panel!</i>`
    await notifyAdmin(adminMsg).catch(console.error)
  }
}

// ============================================
// ACCOUNT DELIVERY
// ============================================
export async function notifyAccountDelivery(user: any, orderData: {
  name: string
  orderId: string
  productName: string
  email: string
  password: string
  extra?: string
}) {
  // 1. Email
  if (user.email) {
    await sendAccountDeliveryEmail(user.email, orderData).catch(console.error)
  }

  const message = `📦 <b>Akun Premium Siap!</b>\n\nHi ${orderData.name},\nPesanan <b>${orderData.productName}</b> kamu sudah siap.\n\nEmail: <code>${orderData.email}</code>\nPassword: <code>${orderData.password}</code>\n${orderData.extra ? `Info: ${orderData.extra}\n` : ''}\n⚠️ <i>Segera ganti password setelah login!</i>`

  // 2. WA
  if (user.whatsappNumber) {
    await sendWaNotification(user.whatsappNumber, message).catch(console.error)
  }

  // 3. Telegram
  if (user.telegramId) {
    await sendTelegramNotification(user.telegramId, message).catch(console.error)
  }
}

// ============================================
// PAYMENT SUCCESS (+ Admin notif)
// ============================================
export async function notifyPaymentSuccess(user: any, data: {
  name: string
  amount: number
  type: 'wallet' | 'order'
  description: string
}) {
  // 1. Email
  if (user.email) {
    await sendPaymentSuccessEmail(user.email, data).catch(console.error)
  }

  const userMsg = `💰 <b>Pembayaran Berhasil!</b>\n\nHi ${data.name},\nPembayaran kamu telah dikonfirmasi.\n\nTotal: Rp ${data.amount.toLocaleString('id-ID')}\nKeterangan: ${data.description}`

  // 2. WA
  if (user.whatsappNumber) {
    await sendWaNotification(user.whatsappNumber, userMsg).catch(console.error)
  }

  // 3. Telegram
  if (user.telegramId) {
    await sendTelegramNotification(user.telegramId, userMsg).catch(console.error)
  }

  // 4. Notify admin for wallet topup (optional)
  if (data.type === 'wallet') {
    const adminMsg = `💳 <b>Topup Saldo Masuk!</b>\n\n👤 User: ${data.name} (${user.email})\n💰 Jumlah: Rp ${data.amount.toLocaleString('id-ID')}`
    await notifyAdmin(adminMsg).catch(console.error)
  }
}

// ============================================
// ORDER FAILED (Refund notif to user + admin)
// ============================================
export async function notifyOrderFailed(user: any, orderData: {
  orderId: string
  productName: string
  price: number
  reason?: string
}) {
  const userMsg = `❌ <b>Pesanan Gagal - Saldo Dikembalikan</b>\n\nHi ${user.name},\nMaaf, pesanan kamu gagal diproses.\n\nOrder ID: #${orderData.orderId.slice(-8).toUpperCase()}\nProduk: ${orderData.productName}\nSaldo dikembalikan: Rp ${orderData.price.toLocaleString('id-ID')}`

  if (user.email && user.email) {
    // Piggyback payment success email as refund notification
    await sendPaymentSuccessEmail(user.email, {
      name: user.name,
      amount: orderData.price,
      type: 'order',
      description: `Refund otomatis - ${orderData.productName}`
    }).catch(console.error)
  }

  if (user.whatsappNumber) {
    await sendWaNotification(user.whatsappNumber, userMsg).catch(console.error)
  }

  if (user.telegramId) {
    await sendTelegramNotification(user.telegramId, userMsg).catch(console.error)
  }

  const adminMsg = `⚠️ <b>Order Gagal!</b>\n\n👤 User: ${user.name} (${user.email})\n📦 Produk: ${orderData.productName}\n💰 Refund: Rp ${orderData.price.toLocaleString('id-ID')}\n${orderData.reason ? `\nAlasan: ${orderData.reason}` : ''}`
  await notifyAdmin(adminMsg).catch(console.error)
}
