import { NextRequest, NextResponse } from 'next/server';
import db from '@/lib/db';

// BMR Calculation using Mifflin-St Jeor Equation (most accurate)
function calculateBMR(weight: number, height: number, age: number, sex: string): number {
  // Weight in kg, height in cm
  if (sex.toLowerCase() === 'male') {
    return (10 * weight) + (6.25 * height) - (5 * age) + 5;
  } else {
    return (10 * weight) + (6.25 * height) - (5 * age) - 161;
  }
}

// TDEE with activity multiplier
function calculateTDEE(bmr: number, activityLevel: string): number {
  const multipliers: Record<string, number> = {
    'sedentary': 1.2,
    'lightly active': 1.375,
    'moderately active': 1.55,
    'very active': 1.725,
    'extra active': 1.9
  };
  
  // Normalize key
  const key = Object.keys(multipliers).find(k => activityLevel?.toLowerCase().includes(k)) || 'moderately active';
  return Math.round(bmr * (multipliers[key] || 1.55));
}

// Goal-based calorie adjustment
function adjustCaloriesForGoal(tdee: number, goal: string, daysPerWeek?: string): number {
  const weeklyGoalTarget = 500; // 500 cal deficit/surplus per day
  
  if (goal.includes('weight-loss') || goal.includes('loss')) {
    return Math.max(1200, tdee - weeklyGoalTarget); // Minimum 1200 cal
  }
  if (goal.includes('muscle-gain') || goal.includes('gain')) {
    return tdee + weeklyGoalTarget + 300; // Slight surplus +300
  }
  if (goal.includes('endurance')) {
    return tdee + 200; // Slight surplus for endurance
  }
  if (goal.includes('strength')) {
    return tdee + 100; // Maintenance plus minimal surplus
  }
  return tdee; // general health = maintenance
}

// Macro distribution based on goal (percentages)
function calculateMacros(calories: number, goal: string, dietary: string[] = []): {
  protein: number;
  carbs: number;
  fats: number;
} {
  let proteinPct = 0.25;  // default 25%
  let carbsPct = 0.45;    // default 45%
  let fatsPct = 0.30;     // default 30%

  if (goal.includes('muscle-gain') || goal.includes('strength')) {
    proteinPct = 0.35;
    carbsPct = 0.40;
    fatsPct = 0.25;
  }
  if (goal.includes('weight-loss')) {
    proteinPct = 0.40; // higher protein for satiety
    carbsPct = 0.30;
    fatsPct = 0.30;
  }
  if (goal.includes('endurance')) {
    proteinPct = 0.20;
    carbsPct = 0.60;
    fatsPct = 0.20;
  }

  // Adjust for dietary patterns
  if (dietary.includes('keto') || dietary.includes('paleo')) {
    carbsPct = 0.10;
    fatsPct = 0.70;
    proteinPct = 0.20;
  }
  if (dietary.includes('vegan') || dietary.includes('vegetarian')) {
    proteinPct = 0.30; // slightly higher
    fatsPct = 0.30;
    carbsPct = 0.40;
  }

  const proteinCals = calories * proteinPct;
  const carbsCals = calories * carbsPct;
  const fatsCals = calories * fatsPct;

  return {
    protein: Math.round(proteinCals / 4),  // 4 cal/g
    carbs: Math.round(carbsCals / 4),      // 4 cal/g
    fats: Math.round(fatsCals / 9)         // 9 cal/g
  };
}

// Cultural meal templates based on dietary preferences + region hint (from user goals)
function generateMealPlan(
  calories: number, 
  macros: { protein: number; carbs: number; fats: number },
  goal: string,
  dietary: string[] = [],
  cuisine?: string  // 'african', 'western', 'asian', 'mediterranean'
): {
  breakfast: string;
  lunch: string;
  dinner: string;
  snacks: string[];
  groceryList: string[];
  macroTargets: { protein: number; carbs: number; fats: number };
  totalCalories: number;
  cuisine: string;
} {
  // Default to African if not specified (user base is likely African based on KES currency)
  const cuisineType = cuisine || 'african';

  // Meal templates by cuisine + goal
  const mealTemplates: Record<string, Record<string, { breakfast: string; lunch: string; dinner: string; snacks: string[] }>> = {
    african: {
      'weight-loss': {
        breakfast: 'Scrambled eggs with spinach and tomatoes (2 eggs) + 1 slice whole-grain toast',
        lunch: 'Grilled tilapia (150g) with steamed sukuma wiki and 1 small ugali',
        dinner: 'Chicken vegetable soup (skinless chicken breast, carrots, onions, kale)',
        snacks: ['Greek yogurt with honey', '1 apple', '30g roasted peanuts']
      },
      'muscle-gain': {
        breakfast: '3-egg omelet with cheese + 2 slices whole-grain bread + 1 cup milk',
        lunch: 'Grilled beef stew (200g lean beef) with rice (1.5 cups) + vegetable salad',
        dinner: 'Baked chicken thighs (2 pcs) with roasted sweet potatoes and green peas',
        snacks: ['Peanut butter banana smoothie', 'Hard-boiled eggs (2 pcs)', 'Mixed nuts (50g)']
      },
      'general': {
        breakfast: 'Porridge (ugali/oatmeal) with milk and honey + 1 boiled egg',
        lunch: 'Githeri (maize + beans) with vegetable salad + 1 piece fruit',
        dinner: 'Steamed fish with lemon + chapati (1 small) + sautéed greens',
        snacks: ['Fresh fruit (mango/banana)', 'Roasted maize', 'Yogurt']
      },
      'endurance': {
        breakfast: 'Large bowl of oatmeal with banana + 2 tbsp peanut butter + milk',
        lunch: 'Pilau rice with chickpeas and vegetables + grilled chicken',
        dinner: 'Pasta with meat sauce + large side salad + garlic bread',
        snacks: ['Energy balls (dates + oats + nuts)', 'Smoothie', 'Granola bar']
      },
      'strength': {
        breakfast: '3-egg scramble with minced beef + 2 slices toast',
        lunch: 'Grilled steak (200g) with rice and mixed vegetables',
        dinner: 'Goat meat stew with potatoes and carrots + whole grain bread',
        snacks: ['Protein shake', 'Beef jerky', 'Tuna sandwich']
      }
    },
    western: {
      'muscle-gain': {
        breakfast: 'Protein oats (1 cup oats + 2 scoops whey + banana + almond butter)',
        lunch: 'Grilled chicken breast (200g) + brown rice (1.5 cups) + broccoli',
        dinner: 'Lean beef steak (200g) + sweet potato mash + asparagus',
        snacks: ['Greek yogurt with granola', 'Protein shake', 'Cottage cheese with berries']
      },
      'weight-loss': {
        breakfast: 'Egg white omelet with veggies + 1 piece whole wheat toast',
        lunch: 'Grilled salmon salad (mixed greens, avocado, lemon dressing)',
        dinner: 'Baked chicken breast with quinoa and steamed vegetables',
        snacks: ['Apple slices with almond butter', 'Celery + hummus', 'Protein shake']
      },
      'general': {
        breakfast: 'Avocado toast (2 slices) + poached eggs (2) + orange juice',
        lunch: 'Turkey sandwich on whole grain + side salad',
        dinner: 'Pasta with marinara sauce + lean ground turkey + Parmesan',
        snacks: ['Mixed nuts', 'Greek yogurt', 'Apple']
      },
      'endurance': {
        breakfast: 'Whole grain pancakes with maple syrup + bacon + eggs',
        lunch: 'Turkey chili with beans + cornbread',
        dinner: 'Pasta with meatballs + garlic bread + side salad',
        snacks: ['Banana', 'Trail mix', 'Chocolate milk']
      },
      'strength': {
        breakfast: 'Steak and eggs (3 eggs, 150g steak) + toast',
        lunch: 'Protein burrito (chicken, rice, beans, cheese)',
        dinner: 'Pot roast with potatoes and carrots',
        snacks: ['Cottage cheese', 'Protein bar', 'Tuna']
      }
    },
    mediterranean: {
      'general': {
        breakfast: 'Greek yogurt with honey, walnuts, and fresh figs',
        lunch: 'Greek salad (cucumber, tomatoes, olives, feta) with pita bread',
        dinner: 'Grilled lamb kebabs with tzatziki + couscous + grilled vegetables',
        snacks: ['Olives + cheese', 'Hummus + carrots', 'Fresh figs']
      },
      'muscle-gain': {
        breakfast: 'Scrambled eggs with feta + whole grain pita + olive oil',
        lunch: 'Grilled chicken souvlaki with gyro rice + tzatziki',
        dinner: 'Baked Mediterranean fish with roasted vegetables + quinoa',
        snacks: ['Greek yogurt + honey', 'Nuts mix', 'Protein smoothie']
      },
      'weight-loss': {
        breakfast: 'Greek yogurt + cucumber + dill + 1 slice whole grain',
        lunch: 'Tuna salad with lemon-olive oil dressing + mixed greens',
        dinner: 'Grilled white fish + steamed artichokes + side salad',
        snacks: ['Celery + tzatziki', 'Green olives', 'Herbal tea']
      },
      'endurance': {
        breakfast: 'Oatmeal with honey + dried figs + walnuts',
        lunch: 'Chickpea salad with olive oil + whole grain bread',
        dinner: 'Pasta with tomato sauce + lean ground lamb + feta cheese',
        snacks: ['Dried apricots', 'Energy bar', 'Smoothie']
      },
      'strength': {
        breakfast: '3-egg omelet with feta + olives + whole grain toast',
        lunch: 'Grilled lamb kebabs (200g) + rice pilaf + Greek salad',
        dinner: 'Seafood (shrimp + fish) stew with tomatoes + crusty bread',
        snacks: ['Cottage cheese', 'Mixed nuts', 'Protein shake']
      }
    },
    asian: {
      'general': {
        breakfast: 'Congee (rice porridge) with shredded chicken + scallions',
        lunch: 'Chicken stir-fry with vegetables + brown rice',
        dinner: 'Grilled fish with ginger-scallion sauce + steamed vegetables + rice',
        snacks: ['Fresh mango', 'Steamed egg', 'Green tea']
      },
      'muscle-gain': {
        breakfast: 'Beef noodles soup + 2 boiled eggs',
        lunch: 'Teriyaki chicken bowl (200g chicken) + rice + edamame',
        dinner: 'Korean BBQ beef (bulgogi) + rice + kimchi + vegetable soup',
        snacks: ['Protein shake with banana', 'Rice cakes + peanut butter', 'Soy milk']
      },
      'weight-loss': {
        breakfast: 'Miso soup + steamed fish + small bowl rice',
        lunch: 'Salmon sashimi salad with ginger-sesame dressing',
        dinner: 'Steamed fish with ginger + vegetable stir-fry (no oil) + small rice',
        snacks: ['Green tea', 'Cucumber slices', 'Edamame']
      },
      'endurance': {
        breakfast: 'Rice porridge with egg + pickled vegetables',
        lunch: 'Chicken and vegetable fried rice (large portion) + miso soup',
        dinner: 'Beef and noodle soup (pho style) + extra meat + vegetables',
        snacks: ['Banana', 'Energy drink', 'Rice pudding']
      },
      'strength': {
        breakfast: 'Steak and eggs + small rice',
        lunch: 'Pork katsu with rice + miso soup + shredded cabbage',
        dinner: 'BBQ short ribs + kimchi fried rice + egg',
        snacks: ['Tuna on rice cakes', 'Protein bar', 'Soy yogurt']
      }
    }
  };

  const cuisinePlan = mealTemplates[cuisineType]?.[primaryGoal(goal)] || mealTemplates['african']['general'];

  // Daily targets from macros
  const { protein, carbs, fats } = macros;

  return {
    breakfast: cuisinePlan.breakfast,
    lunch: cuisinePlan.lunch,
    dinner: cuisinePlan.dinner,
    snacks: cuisinePlan.snacks.slice(0, 2),
    groceryList: [],
    macroTargets: { protein, carbs, fats },
    totalCalories: calories,
    cuisine: cuisineType
  };
}

function primaryGoal(goal: string): string {
  if (goal.includes('muscle-gain')) return 'muscle-gain';
  if (goal.includes('weight-loss')) return 'weight-loss';
  if (goal.includes('endurance')) return 'endurance';
  if (goal.includes('strength')) return 'strength';
  return 'general';
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const {
      age, height, weight, sex,
      fitness_level,
      goals,           // array
      equipment,
      dietary,
      calories_target,  // '1200-1500' etc or 'auto'
      calculated_calories, // if frontend did BMR calc already
      focus = 'workout'
    } = body;

    if (!weight || !height || !age || !sex) {
      return NextResponse.json({ error: 'Missing required fields: weight, height, age, sex' }, { status: 400 });
    }

    // 1. Calculate BMR & TDEE
    const bmr = calculateBMR(parseFloat(weight), parseFloat(height), parseInt(age), sex);
    const tdee = calculateTDEE(bmr, body.activity_level || 'moderately active');

    // 2. Determine calorie target
    let dailyCalories: number;
    if (calculated_calories) {
      dailyCalories = calculated_calories;
    } else if (calories_target === 'auto') {
      dailyCalories = adjustCaloriesForGoal(tdee, goals[0] || 'general', body.days_per_week);
    } else {
      // Parse range: '1200-1500' -> take midpoint
      const [min, max] = (calories_target || '1500-1800').split('-').map(Number);
      dailyCalories = Math.round((min + max) / 2);
    }

    // 3. Calculate macros
    const macros = calculateMacros(dailyCalories, goals[0] || 'general', dietary);

    // 4. Detect cuisine preference from goals or dietary (simple heuristic)
    let cuisine = 'western';
    if (dietary?.includes('african') || goals?.some((g: string) => g.includes('african'))) cuisine = 'african';
    if (dietary?.includes('mediterranean')) cuisine = 'mediterranean';
    if (dietary?.includes('asian')) cuisine = 'asian';

    // 5. Generate meal plan
    const mealPlan = generateMealPlan(dailyCalories, macros, goals[0] || 'general', dietary, cuisine);

    // 6. Generate weekly plan (repeat with slight variations or pre-made templates)
    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    const weeklyMeals = days.map(day => ({
      day,
      breakfast: day === 'Saturday' ? 'Protein pancakes with fruit' : mealPlan.breakfast,
      lunch: day === 'Sunday' ? 'Large family meal with balanced macros' : mealPlan.lunch,
      dinner: mealPlan.dinner,
      snacks: mealPlan.snacks
    }));

    return NextResponse.json({
      id: `meal_${Date.now()}`,
      dailyTargets: mealPlan,
      weeklyPlan: weeklyMeals,
      nutrition: {
        dailyCalories,
        macros,
        bmr: Math.round(bmr),
        tdee: Math.round(tdee)
      }
    });
  } catch (error: any) {
    console.error('Meal generation error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}