const { TelegramBot } = require('node-telegram-bot-api');
const path = require('path');
const fs = require('fs');
const { getRoom, addMessage, setRoomBlocked, setRoomStatus } = require('./db');

const UPLOAD_DIR = path.join(__dirname, 'public', 'uploads');
fs.mkdirSync(UPLOAD_DIR, { recursive: true });

// escape karakter spesial Markdown Telegram (_ * ` [) biar nama file/nama user
// yang mengandung karakter itu (mis. IMG_2024_01.jpg) gak bikin Telegram nolak pesan
function escapeMd(text) {
  return String(text == null ? '' : text).replace(/([_*`[])/g, '\\$1');
}

function initBot({ token, adminChatId, io }) {
  const bot = new TelegramBot(token, { polling: true });

  bot.on('polling_error', (err) => {
    console.error('[Telegram polling_error]', err.message);
  });

  // Kirim notifikasi pesan baru dari visitor ke grup admin
  function notifyNewChat(room) {
    const text =
      `💬 *LIVECHAT BARU DIBUKA*\n\n` +
      `🆔 Room ID: ${room.id}\n` +
      `👤 User: ${escapeMd(room.user)}\n` +
      (room.email ? `✉️ Email: ${escapeMd(room.email)}\n` : '') +
      `🌐 Site: ${escapeMd(room.site)}\n\n` +
      `Balas:\n\`/reply ${room.id} isi_pesan\``;

    return bot.sendMessage(adminChatId, text, { parse_mode: 'Markdown' });
  }

  function notifyNewMessage(room, message) {
    const text =
      `💬 *Pesan Livechat*\n\n` +
      `🆔 Room ID: ${room.id}\n` +
      `User: ${escapeMd(room.user)}\n` +
      `Pesan: ${escapeMd(message)}\n\n` +
      `Balas:\n\`/reply ${room.id} isi_pesan\``;

    return bot.sendMessage(adminChatId, text, { parse_mode: 'Markdown' });
  }

  // Kirim notifikasi gambar/file baru dari visitor ke grup admin
  function notifyNewFile(room, { type, filePath, filename }) {
    const caption =
      `💬 *File dari Livechat*\n\n` +
      `User: ${escapeMd(room.user)}\n` +
      `File: ${escapeMd(filename)}\n\n` +
      `Balas:\n\`/reply ${room.id} isi_pesan\`\n` +
      `(atau kirim foto/dokumen dengan caption \`/reply ${room.id}\`)`;

    if (type === 'image') {
      return bot.sendPhoto(adminChatId, filePath, { caption, parse_mode: 'Markdown' });
    }
    return bot.sendDocument(adminChatId, filePath, { caption, parse_mode: 'Markdown' });
  }

  // Notif ke admin waktu chat ditutup otomatis karena nganggur
  function notifyRoomClosed(room, minutes) {
    const text =
      `⏱️ *Chat Auto-Closed*\n\n` +
      `🆔 Room ID: ${room.id}\n` +
      `User: ${escapeMd(room.user)}\n\n` +
      `Chat ditutup otomatis karena tidak ada aktivitas selama ${minutes} menit.`;

    return bot.sendMessage(adminChatId, text, { parse_mode: 'Markdown' });
  }

  // Command: /reply {room_id} {pesan}
  bot.onText(/^\/reply (\d+) (.+)/s, (msg, match) => {
    const chatId = msg.chat.id;
    const roomId = match[1];
    const replyText = match[2];

    const room = getRoom(roomId);
    if (!room) {
      bot.sendMessage(chatId, `⚠️ Room #${roomId} tidak ditemukan.`);
      return;
    }

    // simpan balasan admin
    addMessage({ room_id: roomId, from: 'admin', text: replyText, type: 'text' });

    // kirim realtime ke widget di website lewat socket.io
    io.to(`room_${roomId}`).emit('admin_reply', {
      room_id: Number(roomId),
      text: replyText,
      type: 'text',
      ts: new Date().toISOString(),
    });

    bot.sendMessage(chatId, `✅ Balasan terkirim ke Room #${roomId}`);
  });

  // Command: /block {room_id} atau /suspend {room_id}
  bot.onText(/^\/(block|suspend) (\d+)/, (msg, match) => {
    const chatId = msg.chat.id;
    const roomId = match[2];

    const room = getRoom(roomId);
    if (!room) {
      bot.sendMessage(chatId, `⚠️ Room #${roomId} tidak ditemukan.`);
      return;
    }

    setRoomBlocked(roomId, true);

    io.to(`room_${roomId}`).emit('room_blocked', {
      room_id: Number(roomId),
      ts: new Date().toISOString(),
    });

    bot.sendMessage(chatId, `🚫 Room #${roomId} (${room.user}) diblokir. Visitor tidak bisa kirim pesan lagi.`);
  });

  // Command: /unblock {room_id} atau /unsuspend {room_id}
  bot.onText(/^\/(unblock|unsuspend) (\d+)/, (msg, match) => {
    const chatId = msg.chat.id;
    const roomId = match[2];

    const room = getRoom(roomId);
    if (!room) {
      bot.sendMessage(chatId, `⚠️ Room #${roomId} tidak ditemukan.`);
      return;
    }

    setRoomBlocked(roomId, false);
    setRoomStatus(roomId, 'open');

    io.to(`room_${roomId}`).emit('room_unblocked', {
      room_id: Number(roomId),
      ts: new Date().toISOString(),
    });

    bot.sendMessage(chatId, `✅ Room #${roomId} (${room.user}) dibuka blokirnya. Visitor bisa chat lagi.`);
  });

  // Admin balas dengan FOTO, caption: /reply {room_id} [pesan opsional]
  bot.on('photo', async (msg) => {
    const caption = msg.caption || '';
    const match = caption.match(/^\/reply (\d+)\s*(.*)$/s);
    if (!match) return; // foto tanpa caption /reply diabaikan

    const chatId = msg.chat.id;
    const roomId = match[1];
    const extraText = match[2] ? match[2].trim() : '';

    const room = getRoom(roomId);
    if (!room) {
      bot.sendMessage(chatId, `⚠️ Room #${roomId} tidak ditemukan.`);
      return;
    }

    try {
      // ambil resolusi foto paling besar
      const fileId = msg.photo[msg.photo.length - 1].file_id;
      const localPath = await bot.downloadFile(fileId, UPLOAD_DIR);
      const filename = path.basename(localPath);
      const url = '/uploads/' + filename;

      addMessage({
        room_id: roomId,
        from: 'admin',
        text: extraText || filename,
        type: 'image',
        url,
        filename,
      });

      io.to(`room_${roomId}`).emit('admin_reply', {
        room_id: Number(roomId),
        text: extraText,
        type: 'image',
        url,
        filename,
        ts: new Date().toISOString(),
      });

      bot.sendMessage(chatId, `✅ Gambar terkirim ke Room #${roomId}`);
    } catch (err) {
      console.error('[bot photo reply error]', err.message);
      bot.sendMessage(chatId, `❌ Gagal mengirim gambar ke Room #${roomId}`);
    }
  });

  // Admin balas dengan DOKUMEN, caption: /reply {room_id} [pesan opsional]
  bot.on('document', async (msg) => {
    const caption = msg.caption || '';
    const match = caption.match(/^\/reply (\d+)\s*(.*)$/s);
    if (!match) return; // dokumen tanpa caption /reply diabaikan

    const chatId = msg.chat.id;
    const roomId = match[1];
    const extraText = match[2] ? match[2].trim() : '';

    const room = getRoom(roomId);
    if (!room) {
      bot.sendMessage(chatId, `⚠️ Room #${roomId} tidak ditemukan.`);
      return;
    }

    try {
      const fileId = msg.document.file_id;
      const localPath = await bot.downloadFile(fileId, UPLOAD_DIR);
      const filename = msg.document.file_name || path.basename(localPath);
      const url = '/uploads/' + path.basename(localPath);
      const isImage = (msg.document.mime_type || '').startsWith('image/');

      addMessage({
        room_id: roomId,
        from: 'admin',
        text: extraText || filename,
        type: isImage ? 'image' : 'file',
        url,
        filename,
      });

      io.to(`room_${roomId}`).emit('admin_reply', {
        room_id: Number(roomId),
        text: extraText,
        type: isImage ? 'image' : 'file',
        url,
        filename,
        ts: new Date().toISOString(),
      });

      bot.sendMessage(chatId, `✅ File terkirim ke Room #${roomId}`);
    } catch (err) {
      console.error('[bot document reply error]', err.message);
      bot.sendMessage(chatId, `❌ Gagal mengirim file ke Room #${roomId}`);
    }
  });

  return { bot, notifyNewChat, notifyNewMessage, notifyNewFile, notifyRoomClosed };
}

module.exports = { initBot };
