import TelegramBot from 'node-telegram-bot-api';
import cron from 'node-cron';
import dotenv from 'dotenv';
dotenv.config();

const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN!, { polling: true });

// ── Daily keto tips ────────────────────────────────────────────────
const KETO_TIPS = [
  "💧 Drink at least 2–3L of water today. Keto increases water loss!",
  "🥑 Add avocado to your next meal. It's the perfect keto fat source with 15g of healthy fat.",
  "🧂 Feeling tired? Your electrolytes may be low. Add a pinch of pink Himalayan salt to your water.",
  "🥩 Protein goal: aim for 1.6g per kg of body weight to preserve muscle while in ketosis.",
  "🌿 MCT oil in your morning coffee can kickstart ketone production. Start with 1 tsp.",
  "🔢 Net carbs = Total carbs - Fiber. Always count NET carbs, not total!",
  "😴 Poor sleep raises cortisol and kicks you out of ketosis. Aim for 7-9 hours.",
  "🏃 Fasted morning walks accelerate fat burning while in keto. Try 20-30 min tomorrow!",
  "🧀 Cheese is 0.4g net carbs per slice — guilt-free keto snack!",
  "⚡ If you're tired in week 1, that's 'keto flu'. It passes in 2-3 days. Electrolytes help!",
  "🥚 Eggs are the most complete keto food — protein, fat, vitamins, and nearly 0 carbs.",
  "🌰 Almonds, macadamia, and pecans are your best keto nut options. Avoid cashews!",
  "💊 Consider supplementing magnesium glycinate — most keto dieters are deficient.",
  "🫙 Meal prep Sunday: cook a batch of eggs, bacon and veggies for a seamless keto week.",
  "📊 Track your macros for at least the first 30 days. It builds intuitive keto awareness."
];

// ── Macro guide ────────────────────────────────────────────────────
const MACRO_INFO = `
📊 *Standard Keto Macros*:

🥑 *Fat*: 65–75% of calories
🥩 *Protein*: 20–30% of calories  
🥬 *Net Carbs*: 5–10% (max 20–25g/day)

*Quick examples* (100g serving):
• Chicken breast: 31g protein, 3.6g fat, 0g carbs ✅
• Avocado: 2g protein, 15g fat, 2g net carbs ✅
• White rice: 28g carbs ❌ (skip it!)
• Cauliflower: 3g net carbs ✅ (great rice sub)

Use /log to track your daily intake!
`;

// ── Store connected users (in production, use DB) ─────────────────
const connectedUsers = new Map<number, { userId?: string; name?: string }>();

// ── /start ────────────────────────────────────────────────────────
bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  const name = msg.from?.first_name || 'Keto Friend';

  connectedUsers.set(chatId, { name });

  bot.sendMessage(chatId, `
🥑 *Welcome to TheKetoBay Bot, ${name}!*

I'm your daily keto companion. Here's what I can do:

/tip — Get today's keto tip
/macros — Keto macro guide
/log — Log your daily macros
/streak — Check your streak
/plan — Link your account for personalized tips
/shop — Keto product recommendations
/motivation — Get motivated 💪
/help — Show all commands

You'll also receive:
• Daily keto tips at 8:00 AM 🌅
• Streak reminders at 8:00 PM 🔥
• New plan notifications 🆕

Let's crush your keto goals! 💪
  `, { parse_mode: 'Markdown' });
});

// ── /tip ──────────────────────────────────────────────────────────
bot.onText(/\/tip/, (msg) => {
  const tip = KETO_TIPS[Math.floor(Math.random() * KETO_TIPS.length)];
  bot.sendMessage(msg.chat.id, `*Today's Keto Tip:*\n\n${tip}`, { parse_mode: 'Markdown' });
});

// ── /macros ───────────────────────────────────────────────────────
bot.onText(/\/macros/, (msg) => {
  bot.sendMessage(msg.chat.id, MACRO_INFO, { parse_mode: 'Markdown' });
});

// ── /log <calories> <protein> <carbs> ────────────────────────────
bot.onText(/\/log (.+)/, async (msg, match) => {
  const chatId = msg.chat.id;
  const parts = match?.[1]?.split(' ') || [];

  const calories = parseInt(parts[0]);
  const protein = parseInt(parts[1] || '0');
  const carbs = parseInt(parts[2] || '0');

  if (isNaN(calories)) {
    return bot.sendMessage(chatId,
      '📝 *Logging format:*\n`/log <calories> <protein_g> <net_carbs_g>`\n\n*Example:* `/log 1800 120 18`',
      { parse_mode: 'Markdown' }
    );
  }

  const carbStatus = carbs <= 20 ? '✅ In ketosis range!' : carbs <= 30 ? '⚠️ Close to limit' : '❌ Over keto limit!';

  bot.sendMessage(chatId, `
✅ *Daily Log Saved!*

🔥 Calories: *${calories} kcal*
🥩 Protein: *${protein}g*
🥬 Net Carbs: *${carbs}g* ${carbStatus}

${carbs <= 20 ? "Great job staying in ketosis! 🎉" : "Consider reducing carbs to stay in ketosis."}

Log on the website for detailed tracking: ${process.env.FRONTEND_URL}/tracker
  `, { parse_mode: 'Markdown' });
});

// ── /streak ───────────────────────────────────────────────────────
bot.onText(/\/streak/, (msg) => {
  const chatId = msg.chat.id;
  const user = connectedUsers.get(chatId);

  bot.sendMessage(chatId, `
🔥 *Streak Tracker*

Connect your TheKetoBay account to see your streak here!

👉 ${process.env.FRONTEND_URL}/settings

Once connected, I'll remind you daily to maintain your streak and celebrate your milestones!

🏆 *Streak Milestones:*
• 7 days: Keto Starter badge
• 14 days: Keto Committed badge  
• 30 days: Keto Warrior badge
• 60 days: Keto Legend badge
  `, { parse_mode: 'Markdown' });
});

// ── /shop ─────────────────────────────────────────────────────────
bot.onText(/\/shop/, (msg) => {
  bot.sendMessage(msg.chat.id, `
🛒 *Keto Marketplace*

Top picks this week:

🥥 MCT Oil — Pure energy for ketosis
💊 Electrolyte Complex — Beat keto flu
🍫 Keto Dark Chocolate (85%+) — Guilt-free treat
🥜 Macadamia Nut Butter — Perfect fat source

Browse all products:
👉 ${process.env.FRONTEND_URL}/marketplace

Use code *TELEGRAM10* for 10% off your first order! 🎁
  `, { parse_mode: 'Markdown' });
});

// ── /motivation ───────────────────────────────────────────────────
const MOTIVATIONS = [
  "💪 Every meal is a choice. Every choice is progress. You've got this!",
  "🔥 The keto flu is temporary. The results are permanent. Push through!",
  "🥑 Your body is literally becoming a fat-burning machine right now. Keep going!",
  "⚡ Energy, clarity, confidence — they're all on the other side of ketosis.",
  "🏆 Most people quit in week 1. You're still here. That already makes you extraordinary.",
  "💡 Remember why you started. That reason is bigger than any craving.",
  "🌟 Ketosis isn't just a diet. It's a superpower. Own it."
];

bot.onText(/\/motivation/, (msg) => {
  const motivation = MOTIVATIONS[Math.floor(Math.random() * MOTIVATIONS.length)];
  bot.sendMessage(msg.chat.id, motivation);
});

// ── /help ─────────────────────────────────────────────────────────
bot.onText(/\/help/, (msg) => {
  bot.sendMessage(msg.chat.id, `
🥑 *TheKetoBay Bot Commands*

/start — Welcome message
/tip — Random keto tip
/macros — Macro breakdown guide
/log <cal> <protein> <carbs> — Log your day
/streak — Check your streak
/shop — Product recommendations
/motivation — Daily motivation
/plan — Link your account
/help — This message

📱 Full features on the website:
${process.env.FRONTEND_URL}
  `, { parse_mode: 'Markdown' });
});

// ── CRON JOBS ─────────────────────────────────────────────────────

// Daily tip at 8:00 AM every day
cron.schedule('0 8 * * *', () => {
  const tip = KETO_TIPS[new Date().getDate() % KETO_TIPS.length];
  connectedUsers.forEach((_, chatId) => {
    bot.sendMessage(chatId, `🌅 *Good Morning, Keto Warrior!*\n\n${tip}\n\n_Have an amazing keto day!_ 🥑`, { parse_mode: 'Markdown' })
      .catch(() => connectedUsers.delete(chatId)); // Remove blocked users
  });
});

// Evening streak reminder at 8:00 PM
cron.schedule('0 20 * * *', () => {
  connectedUsers.forEach((user, chatId) => {
    bot.sendMessage(chatId,
      `🔥 *Evening Check-in!*\n\nDid you log your meals today?\n\n👉 ${process.env.FRONTEND_URL}/tracker\n\nStay consistent — your streak depends on it! 💪`,
      { parse_mode: 'Markdown' }
    ).catch(() => connectedUsers.delete(chatId));
  });
});

// Weekly plan reminder (Mondays at 9:00 AM)
cron.schedule('0 9 * * 1', () => {
  connectedUsers.forEach((_, chatId) => {
    bot.sendMessage(chatId,
      `📅 *New Week, New Keto Goals!*\n\nHave you got your meal plan sorted for this week?\n\n🤖 Generate a personalized AI plan:\n${process.env.FRONTEND_URL}/ai-planner\n\n_It takes just 30 seconds!_ ⚡`,
      { parse_mode: 'Markdown' }
    ).catch(() => connectedUsers.delete(chatId));
  });
});

console.log('🥑 TheKetoBay Telegram Bot is running...');

export { bot };
