import { Context } from "grammy";
import { PortfolioModel, Portfolio } from "../models/Portfolio";
import { getPortfolioMenu, getPortfolioNavKeyboard } from "../menus/mainMenu";

const categoryLabels: Record<string, string> = {
  web: "🌐 Website",
  bot: "🤖 Bot Telegram",
  mobile: "📱 Mobile App",
};

function buildCaption(item: Portfolio, index: number, total: number): string {
  const techList = item.tech
    .split(",")
    .map((t) => `• ${t.trim()}`)
    .join("\n");
  const demoLine = item.demo_url ? `\n🔗 Demo: ${item.demo_url}` : "";

  return (
    `${categoryLabels[item.category] || item.category}\n\n` +
    `📌 *${item.title}*\n\n` +
    `📝 ${item.description}\n\n` +
    `⚙️ *Teknologi:*\n${techList}` +
    demoLine +
    `\n\n_${index + 1} dari ${total}_`
  );
}

// Validasi file_id: harus ada, cukup panjang, bukan URL
function isValidFileId(fileId?: string | null): boolean {
  return !!fileId && fileId.length > 10 && !fileId.startsWith("http");
}

export async function showPortfolioMenu(ctx: Context) {
  const total = PortfolioModel.count();
  if (ctx.callbackQuery) {
    try { await ctx.deleteMessage(); } catch (_) {}
  }
  await ctx.reply(
    `🗂 *Portofolio JD Technolody*\n\nTotal: *${total} project*\n\nPilih kategori:`,
    { parse_mode: "Markdown", reply_markup: getPortfolioMenu() }
  );
}

export async function showPortfolioItem(
  ctx: Context,
  category: string,
  index: number
) {
  const items = PortfolioModel.getByCategory(category);

  if (items.length === 0) {
    await ctx.reply("Belum ada portofolio untuk kategori ini.");
    return;
  }

  const safeIndex = Math.max(0, Math.min(index, items.length - 1));
  const item = items[safeIndex];
  const caption = buildCaption(item, safeIndex, items.length);
  const keyboard = getPortfolioNavKeyboard(category, safeIndex, items.length);

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

  if (isValidFileId(item.media_file_id)) {
    if (item.media_type === "video") {
      await ctx.replyWithVideo(item.media_file_id!, {
        caption,
        parse_mode: "Markdown",
        reply_markup: keyboard,
      });
    } else {
      await ctx.replyWithPhoto(item.media_file_id!, {
        caption,
        parse_mode: "Markdown",
        reply_markup: keyboard,
      });
    }
  } else {
    await ctx.reply(caption, {
      parse_mode: "Markdown",
      reply_markup: keyboard,
      link_preview_options: { is_disabled: true },
    });
  }

}
