import { Context } from "grammy";
import { InlineKeyboard } from "grammy";
import { UserModel } from "../models/User";
import { LeadModel } from "../models/Lead";
import { config } from "../config";

export function isAdmin(ctx: Context): boolean {
  const adminIds = config.ADMIN_CHAT_ID.split(",").map((id) => id.trim());
  return adminIds.includes(String(ctx.from?.id));
}

export async function handleAdminDashboard(ctx: Context) {
  if (!isAdmin(ctx)) {
    await ctx.reply("⛔ Anda tidak memiliki akses admin.");
    return;
  }
  await ctx.reply(
    `🛡 *Admin Dashboard — JD Technolody*\n\nPilih aksi:`,
    {
      parse_mode: "Markdown",
      reply_markup: new InlineKeyboard()
        .text("📊 Statistik", "admin_stats")
        .text("📋 Leads Baru", "admin_leads").row()
        .text("📤 Broadcast", "admin_broadcast_prompt").row(),
    }
  );
}

export async function handleBroadcast(ctx: Context) {
  if (!isAdmin(ctx)) {
    await ctx.reply("⛔ Anda tidak memiliki akses admin.");
    return;
  }

  const text = ctx.message?.text?.replace("/broadcast", "").trim();
  if (!text) {
    await ctx.reply(
      "Format: `/broadcast <pesan>`\nContoh: `/broadcast 🎉 Promo diskon 30% bulan ini!`",
      { parse_mode: "Markdown" }
    );
    return;
  }

  const users = UserModel.getAllSubscribed();
  await ctx.reply(`📤 Broadcast ke ${users.length} user dimulai...`);

  let success = 0;
  let failed = 0;

  for (const user of users) {
    try {
      await ctx.api.sendMessage(
        user.telegram_id,
        `📢 *Update dari JD Technolody*\n\n${text}`,
        { parse_mode: "Markdown" }
      );
      success++;
    } catch (_) {
      failed++;
    }
    await new Promise((r) => setTimeout(r, 50));
  }

  await ctx.reply(
    `✅ Broadcast selesai!\n✅ Berhasil: *${success}*\n❌ Gagal: *${failed}*`,
    { parse_mode: "Markdown" }
  );
}

export async function handleStats(ctx: Context) {
  if (!isAdmin(ctx)) {
    await ctx.reply("⛔ Anda tidak memiliki akses admin.");
    return;
  }

  const totalUsers = UserModel.countAll();
  const subscribedUsers = UserModel.countSubscribed();
  const todayUsers = UserModel.countToday();
  const totalLeads = LeadModel.countAll();
  const newLeads = LeadModel.countByStatus("new");
  const hotLeads = LeadModel.countHot();
  const todayLeads = LeadModel.countToday();

  await ctx.reply(
    `📊 *Statistik Bot JD Technolody*\n\n` +
      `👥 Total User: *${totalUsers}*\n` +
      `🔔 User Subscribe: *${subscribedUsers}*\n` +
      `🆕 User Baru Hari ini: *${todayUsers}*\n\n` +
      `📋 Total Leads: *${totalLeads}*\n` +
      `🆕 Leads Baru: *${newLeads}*\n` +
      `🔥 Hot Leads: *${hotLeads}*\n` +
      `📅 Leads Hari ini: *${todayLeads}*`,
    { parse_mode: "Markdown" }
  );
}

export async function handleLeads(ctx: Context) {
  if (!isAdmin(ctx)) {
    await ctx.reply("⛔ Anda tidak memiliki akses admin.");
    return;
  }

  const leads = LeadModel.getNewLeads(10);

  if (leads.length === 0) {
    await ctx.reply("✅ Tidak ada leads baru.");
    return;
  }

  for (const lead of leads) {
    const hotBadge = lead.is_hot ? "🔥 *HOT LEAD*\n" : "";
    const msg =
      `${hotBadge}` +
      `👤 *${lead.name}*\n` +
      `📱 @${lead.username || "-"} (ID: ${lead.telegram_id})\n` +
      `📞 WA: ${lead.phone_number || "-"}\n` +
      `🛠 ${lead.service_type} | 💰 ${lead.budget}\n` +
      `📌 Project: ${lead.project_name}\n` +
      `⏰ ${lead.created_at}`;

    await ctx.reply(msg, {
      parse_mode: "Markdown",
      reply_markup: new InlineKeyboard()
        .url("💬 Chat", `tg://user?id=${lead.telegram_id}`)
        .url(
          "📞 WA",
          `https://wa.me/${lead.phone_number?.replace(/[^0-9]/g, "") || "0"}`
        ),
    });
  }
}
