import { Context } from "grammy";
import { InlineKeyboard } from "grammy";
import { LeadModel, ServiceType } from "../models/Lead";
import { getConsultationCategoryMenu, getCancelMenu } from "../menus/mainMenu";
import { ServiceCategoryModel } from "../models/ServiceCategory";
import { notifyAdmin } from "../adminBot";

type ConsultStep = "project_name" | "features" | "deadline" | "budget" | "phone";

interface ConsultState {
  step: ConsultStep;
  serviceType: ServiceType;
  serviceLabel: string;
  projectName?: string;
  features?: string;
  deadline?: string;
  budget?: string;
}

const consultStates = new Map<number, ConsultState>();

export function isInConsultation(userId: number): boolean {
  return consultStates.has(userId);
}

export function cancelConsultation(userId: number) {
  consultStates.delete(userId);
}

export async function backConsultation(ctx: Context) {
  const userId = ctx.from!.id;
  const state = consultStates.get(userId);

  try { await ctx.deleteMessage(); } catch (_) {}

  if (!state || state.step === "project_name") {
    consultStates.delete(userId);
    await startConsultation(ctx);
    return;
  }

  const stepMap: Record<ConsultStep, ConsultStep> = {
    features: "project_name",
    deadline: "features",
    budget: "deadline",
    phone: "budget",
    project_name: "project_name",
  };

  const prevStep = stepMap[state.step];
  const stepPrompts: Record<ConsultStep, string> = {
    project_name:
      `📝 *Langkah 1/5 — Nama Project*\n\n` +
      `Apa nama project atau bisnis Anda?\n` +
      `_Contoh: Toko Online Baju Muslim Ibu Sari_`,
    features:
      `💡 *Langkah 2/5 — Fitur yang Dibutuhkan*\n\n` +
      `Sebutkan fitur-fitur utama yang Anda inginkan:\n` +
      `_Contoh: Login, katalog produk, checkout, payment Midtrans, notifikasi WA_`,
    deadline:
      `⏰ *Langkah 3/5 — Target Deadline*\n\n` +
      `Kapan Anda butuhkan project ini selesai?\n` +
      `_Contoh: 2 minggu lagi / Akhir Juli / Tidak ada deadline_`,
    budget:
      `💰 *Langkah 4/5 — Budget*\n\n` +
      `Berapa estimasi budget yang Anda siapkan?\n` +
      `_Contoh: Rp 1.000.000 / Rp 3.000.000 / Masih fleksibel_`,
    phone:
      `📱 *Langkah 5/5 — Nomor WhatsApp*\n\n` +
      `Masukkan nomor WhatsApp agar tim kami bisa menghubungi Anda:\n` +
      `_Contoh: 08123456789 — ketik "skip" untuk lewati_`,
  };

  const clearedFields: Partial<ConsultState> = {};
  if (state.step === "features") clearedFields.projectName = undefined;
  if (state.step === "deadline") clearedFields.features = undefined;
  if (state.step === "budget") clearedFields.deadline = undefined;
  if (state.step === "phone") clearedFields.budget = undefined;

  consultStates.set(userId, { ...state, ...clearedFields, step: prevStep });

  await ctx.reply(stepPrompts[prevStep], {
    parse_mode: "Markdown",
    reply_markup: getCancelMenu(),
  });
}

export async function startConsultation(ctx: Context) {
  if (ctx.callbackQuery) {
    try { await ctx.deleteMessage(); } catch (_) {}
  }

  const categories = ServiceCategoryModel.getAll();
  await ctx.reply(
    `🤖 *Konsultasi AI — JD Technolody*\n\n` +
      `Saya akan membantu menganalisis kebutuhan project dan memberikan estimasi biaya & waktu.\n\n` +
      `Pilih kategori project Anda:`,
    { parse_mode: "Markdown", reply_markup: getConsultationCategoryMenu(categories) }
  );
}

export async function handleConsultCategorySelect(ctx: Context, categorySlug: string) {
  const userId = ctx.from!.id;
  const category = ServiceCategoryModel.getBySlug(categorySlug);
  const label = category ? `${category.icon} ${category.name}` : categorySlug;

  consultStates.set(userId, {
    step: "project_name",
    serviceType: categorySlug as ServiceType,
    serviceLabel: label,
  });

  try { await ctx.deleteMessage(); } catch (_) {}
  await ctx.reply(
    `✅ Kategori: *${label}*\n\n` +
      `📝 *Langkah 1/5 — Nama Project*\n\n` +
      `Apa nama project atau bisnis Anda?\n` +
      `_Contoh: Toko Online Baju Muslim Ibu Sari_`,
    { parse_mode: "Markdown", reply_markup: getCancelMenu() }
  );
}

export async function handleConsultMessage(ctx: Context) {
  const userId = ctx.from!.id;
  const state = consultStates.get(userId);
  if (!state || !ctx.message?.text) return;

  const text = ctx.message.text.trim();

  switch (state.step) {
    case "project_name":
      consultStates.set(userId, { ...state, step: "features", projectName: text });
      await ctx.reply(
        `📌 Project: *${text}*\n\n` +
          `💡 *Langkah 2/5 — Fitur yang Dibutuhkan*\n\n` +
          `Sebutkan fitur-fitur utama yang Anda inginkan:\n` +
          `_Contoh: Login, katalog produk, checkout, payment Midtrans, notifikasi WA_`,
        { parse_mode: "Markdown", reply_markup: getCancelMenu() }
      );
      break;

    case "features":
      consultStates.set(userId, { ...state, step: "deadline", features: text });
      await ctx.reply(
        `✅ Fitur dicatat!\n\n` +
          `⏰ *Langkah 3/5 — Target Deadline*\n\n` +
          `Kapan Anda butuhkan project ini selesai?\n` +
          `_Contoh: 2 minggu lagi / Akhir Juli / Tidak ada deadline_`,
        { parse_mode: "Markdown", reply_markup: getCancelMenu() }
      );
      break;

    case "deadline":
      consultStates.set(userId, { ...state, step: "budget", deadline: text });
      await ctx.reply(
        `⏰ Deadline: *${text}*\n\n` +
          `💰 *Langkah 4/5 — Budget*\n\n` +
          `Berapa estimasi budget yang Anda siapkan?\n` +
          `_Contoh: Rp 1.000.000 / Rp 3.000.000 / Masih fleksibel_`,
        { parse_mode: "Markdown", reply_markup: getCancelMenu() }
      );
      break;

    case "budget":
      consultStates.set(userId, { ...state, step: "phone", budget: text });
      await ctx.reply(
        `💰 Budget: *${text}*\n\n` +
          `📱 *Langkah 5/5 — Nomor WhatsApp*\n\n` +
          `Masukkan nomor WhatsApp agar tim kami bisa menghubungi Anda:\n` +
          `_Contoh: 08123456789 — ketik "skip" untuk lewati_`,
        { parse_mode: "Markdown", reply_markup: getCancelMenu() }
      );
      break;

    case "phone":
      await finishConsultation(ctx, state, text === "skip" ? undefined : text);
      consultStates.delete(userId);
      break;
  }
}

async function finishConsultation(ctx: Context, state: ConsultState, phone?: string) {
  const from = ctx.from!;
  const name = `${from.first_name}${from.last_name ? " " + from.last_name : ""}`;

  try {
    LeadModel.create({
      telegramId: from.id,
      username: from.username,
      name,
      phoneNumber: phone,
      serviceType: state.serviceType,
      projectName: state.projectName!,
      features: state.features!,
      deadline: state.deadline!,
      budget: state.budget!,
    });
  } catch (_) {}

  await ctx.reply(
    `✅ *Analisis Project Anda*\n\n` +
      `📌 *${state.projectName}*\n` +
      `🛠 ${state.serviceLabel}\n\n` +
      `💡 *Fitur:*\n${state.features}\n\n` +
      `⏱ *Estimasi Waktu:* ${estimateDuration(state.serviceType)}\n\n` +
      `📋 _Estimasi biaya akan dikirimkan setelah diskusi detail dengan tim kami._\n\n` +
      `✉️ Tim JD Technolody akan menghubungi Anda dalam *1×24 jam*.\n\n` +
      `_Untuk konsultasi lebih lanjut atau penawaran resmi, gunakan tombol Hubungi Admin di menu._`,
    { parse_mode: "Markdown" }
  );

  const adminMsg =
    `🔔 *NEW LEAD MASUK!*\n\n` +
    `👤 Nama: *${name}*\n` +
    `📱 @${from.username || "-"} (ID: ${from.id})\n` +
    `📞 WA: ${phone || "tidak diisi"}\n\n` +
    `🛠 *${state.serviceLabel}*\n` +
    `📌 Project: *${state.projectName}*\n` +
    `💡 Fitur: ${state.features}\n` +
    `⏰ Deadline: ${state.deadline}\n` +
    `💰 Budget: *${state.budget}*\n\n` +
    `🕐 ${new Date().toLocaleString("id-ID")}\n` +
    `🏷 Status: *NEW LEAD*`;

  const kb = new InlineKeyboard();
  if (from.username) kb.url("💬 Chat Telegram", `https://t.me/${from.username}`);
  if (phone) kb.url("📞 WhatsApp", `https://wa.me/${phone.replace(/[^0-9]/g, "")}`);

  await notifyAdmin(ctx.api, adminMsg, kb.inline_keyboard.length ? kb : undefined);
}

function estimateDuration(serviceType: string): string {
  const map: Record<string, string> = {
    web: "3–30 hari (tergantung paket)",
    apk: "21–60 hari",
    bot: "3–14 hari",
  };
  return map[serviceType] || "Sesuai kompleksitas";
}
