import { Bot, InlineKeyboard } from "grammy";
import { config } from "./config";
import { connectDB } from "./utils/db";
import { saveUser } from "./utils/saveUser";
import { getMainReplyKeyboard } from "./menus/mainMenu";
import { showPortfolioMenu, showPortfolioItem } from "./handlers/portfolio";
import {
  showServicesMenu,
  showServiceCategory,
  showServicePackage,
  buildPriceText,
} from "./handlers/services";
import { showFaq, showTestimonial } from "./handlers/faq";
import {
  startAiConsultation,
  handleAiMessage,
  isInAiConsultation,
  cancelAiConsultation,
  handleOrderNow,
} from "./services/aiConsultant";
import { initAdminBot } from "./adminBot";

const bot = new Bot(config.BOT_TOKEN);

const MENU_BUTTONS = new Set([
  "ℹ️ Tentang Kami",
  "🛠 Layanan",
  "🗂 Portfolio",
  "💰 Harga",
  "🤖 Konsultasi AI",
  "👨‍💼 Hubungi Admin",
  "📢 Channel",
]);

// ─── Konten teks ─────────────────────────────────────────────────────────────

const WELCOME_TEXT =
  `👋 *Selamat datang di JD Technolody!*\n\n` +
  `Kami adalah tim profesional penyedia jasa:\n\n` +
  `🌐 Website Development\n` +
  `🤖 Bot Telegram & WhatsApp Automation\n` +
  `📱 Aplikasi Mobile Android\n` +
  `⚡ Integrasi AI & Automation\n` +
  `⚙️ Custom System Development\n\n` +
  `Gunakan tombol menu di bawah untuk memulai:`;

const ABOUT_TEXT =
  `🏢 *Tentang JD Technolody*\n\n` +
  `Tim developer profesional yang fokus pada solusi digital untuk bisnis Anda.\n\n` +
  `🎯 *Spesialisasi kami:*\n` +
  `• Website (Landing Page, Company Profile, Ecommerce)\n` +
  `• Bot Telegram & Automation\n` +
  `• Aplikasi Android (APK)\n` +
  `• Sistem AI & Integrasi API\n` +
  `• Custom Software Development\n\n` +
  `✅ *Kenapa pilih JD Technolody?*\n` +
  `• Pengerjaan cepat & profesional\n` +
  `• Komunikatif & responsif 24 jam\n` +
  `• Harga terjangkau & transparan\n` +
  `• Garansi bug fix setelah selesai\n` +
  `• Support after-sales\n\n` +
  `📢 Ikuti channel kami: @jdtechnolody`;

// ─── /start & /menu ───────────────────────────────────────────────────────────

bot.command("start", async (ctx) => {
  saveUser(ctx);
  await ctx.reply(WELCOME_TEXT, {
    parse_mode: "Markdown",
    reply_markup: getMainReplyKeyboard(),
  });
});

bot.command("menu", async (ctx) => {
  await ctx.reply(WELCOME_TEXT, {
    parse_mode: "Markdown",
    reply_markup: getMainReplyKeyboard(),
  });
});

// ─── Reply Keyboard handlers ──────────────────────────────────────────────────

bot.hears("ℹ️ Tentang Kami", async (ctx) => {
  await ctx.reply(ABOUT_TEXT, { parse_mode: "Markdown" });
});

bot.hears("🛠 Layanan", async (ctx) => {
  await showServicesMenu(ctx);
});

bot.hears("🗂 Portfolio", async (ctx) => {
  await showPortfolioMenu(ctx);
});

bot.hears("💰 Harga", async (ctx) => {
  await ctx.reply(buildPriceText(), {
    parse_mode: "Markdown",
    reply_markup: new InlineKeyboard().text("🤖 Konsultasi AI", "consultation_start"),
  });
});

bot.hears("🤖 Konsultasi AI", async (ctx) => {
  await startAiConsultation(ctx);
});

bot.hears("👨‍💼 Hubungi Admin", async (ctx) => {
  await ctx.reply(
    `👨‍💼 *Hubungi Admin JD Technolody*\n\n` +
      `Tim kami siap membantu untuk:\n` +
      `• Konsultasi detail project\n` +
      `• Penawaran harga resmi\n` +
      `• Meeting & diskusi teknis\n\n` +
      `Pilih cara menghubungi:`,
    {
      parse_mode: "Markdown",
      reply_markup: new InlineKeyboard()
        .url("💬 Chat Telegram", "https://t.me/jdtechnolody").row()
        .text("🤖 Konsultasi AI dulu", "consultation_start"),
    }
  );
});

bot.hears("📢 Channel", async (ctx) => {
  await ctx.reply(
    `📢 *Channel JD Technolody*\n\n` +
      `Ikuti untuk mendapatkan:\n` +
      `• Update portofolio terbaru\n` +
      `• Promo & penawaran spesial\n` +
      `• Tips & artikel teknologi\n\n` +
      `🔗 @jdtechnolody`,
    {
      parse_mode: "Markdown",
      reply_markup: new InlineKeyboard().url("📢 Join Channel", "https://t.me/jdtechnolody"),
    }
  );
});

// ─── Callback: Portfolio ──────────────────────────────────────────────────────

bot.callbackQuery("portfolio_menu", async (ctx) => {
  await ctx.answerCallbackQuery();
  await showPortfolioMenu(ctx);
});

bot.callbackQuery(/^portfolio_(web|bot|mobile)_(\d+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await showPortfolioItem(ctx, ctx.match[1], parseInt(ctx.match[2]));
});

// ─── Callback: Layanan (3-level) ──────────────────────────────────────────────

bot.callbackQuery("services_menu", async (ctx) => {
  await ctx.answerCallbackQuery();
  await showServicesMenu(ctx);
});

bot.callbackQuery(/^svc_cat_(\w+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await showServiceCategory(ctx, ctx.match[1]);
});

bot.callbackQuery(/^svc_pkg_(\d+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await showServicePackage(ctx, parseInt(ctx.match[1]));
});

bot.callbackQuery(/^svc_back_(\w+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await showServiceCategory(ctx, ctx.match[1]);
});

// ─── Callback: Konsultasi AI ──────────────────────────────────────────────────

bot.callbackQuery("consultation_start", async (ctx) => {
  await ctx.answerCallbackQuery();
  await startAiConsultation(ctx);
});

bot.callbackQuery(/^consult_cat_(\w+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await startAiConsultation(ctx);
});

bot.callbackQuery("order_now", async (ctx) => {
  await ctx.answerCallbackQuery("Memproses pesanan Anda...");
  await handleOrderNow(ctx);
});

bot.callbackQuery("cancel_ai_consult", async (ctx) => {
  await ctx.answerCallbackQuery();
  cancelAiConsultation(ctx.from.id);
  try { await ctx.deleteMessage(); } catch (_) {}
  await ctx.reply("❌ Konsultasi diakhiri. Terima kasih!", { reply_markup: getMainReplyKeyboard() });
});

bot.callbackQuery("main_menu", async (ctx) => {
  await ctx.answerCallbackQuery();
  try { await ctx.deleteMessage(); } catch (_) {}
  await ctx.reply(WELCOME_TEXT, {
    parse_mode: "Markdown",
    reply_markup: getMainReplyKeyboard(),
  });
});

// ─── Callback: FAQ ────────────────────────────────────────────────────────────

bot.callbackQuery(/^faq_(\d+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await showFaq(ctx, parseInt(ctx.match[1]));
});

// ─── Callback: Testimoni ──────────────────────────────────────────────────────

bot.callbackQuery(/^testimonial_(\d+)$/, async (ctx) => {
  await ctx.answerCallbackQuery();
  await showTestimonial(ctx, parseInt(ctx.match[1]));
});

// ─── Callback: Noop ──────────────────────────────────────────────────────────

bot.callbackQuery("noop", async (ctx) => {
  await ctx.answerCallbackQuery();
});

// ─── Text Messages ────────────────────────────────────────────────────────────

bot.on("message:text", async (ctx) => {
  if (MENU_BUTTONS.has(ctx.message.text)) return;

  if (isInAiConsultation(ctx.from.id)) {
    await handleAiMessage(ctx);
    return;
  }

  await ctx.reply(WELCOME_TEXT, {
    parse_mode: "Markdown",
    reply_markup: getMainReplyKeyboard(),
  });
});

// ─── Error Handler ────────────────────────────────────────────────────────────

bot.catch((err) => {
  console.error("Bot error:", err.message);
});

// ─── Main ────────────────────────────────────────────────────────────────────

async function main() {
  connectDB();
  initAdminBot();
  console.log("🚀 Bot utama JD Technolody berjalan...");
  bot.start();
}

main();
