const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Payment = require('../models/Payment');
const MonthlyDraw = require('../models/MonthlyDraw');
const ChitGroup = require('../models/ChitGroup');
const GroupMember = require('../models/GroupMember');
const User = require('../models/User');
const Notification = require('../models/Notification');
const WhatsAppHelper = require('../utils/whatsapp-helper');

/**
 * @route   POST /api/share/payment-receipt
 * @desc    Generate WhatsApp share link for payment receipt
 * @access  Private
 */
router.post('/payment-receipt', auth, async (req, res) => {
  try {
    const { paymentId } = req.body;

    if (!paymentId) {
      return res.status(400).json({
        success: false,
        message: 'Payment ID is required'
      });
    }

    // Get payment with populated references
    const payment = await Payment.findById(paymentId)
      .populate('user_id')
      .populate('group_id');

    if (!payment) {
      return res.status(404).json({
        success: false,
        message: 'Payment not found'
      });
    }

    // Check authorization
    if (payment.user_id._id.toString() !== req.user.id && 
        req.user.role !== 'manager') {
      return res.status(403).json({
        success: false,
        message: 'Not authorized'
      });
    }

    // Generate WhatsApp message
    const message = WhatsAppHelper.generatePaymentReceipt(
      payment,
      payment.group_id,
      payment.user_id
    );

    // Generate WhatsApp link
    const whatsappUrl = WhatsAppHelper.generateShareLink(
      payment.user_id.mobile_number,
      message
    );

    // Log the share action
    await Notification.create({
      type: 'payment_confirmation',
      user_id: payment.user_id._id,
      group_id: payment.group_id._id,
      payment_id: payment._id,
      channel: 'whatsapp',
      message: message,
      status: 'sent'
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        recipient: {
          name: payment.user_id.full_name,
          mobile: payment.user_id.mobile_number
        }
      }
    });
  } catch (error) {
    console.error('Error generating payment receipt share:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/draw-result
 * @desc    Generate WhatsApp share link for draw result
 * @access  Private
 */
router.post('/draw-result', auth, async (req, res) => {
  try {
    const { drawId } = req.body;

    if (!drawId) {
      return res.status(400).json({
        success: false,
        message: 'Draw ID is required'
      });
    }

    // Get draw with populated references
    const draw = await MonthlyDraw.findById(drawId)
      .populate('chit_group_id')
      .populate('winner_id');

    if (!draw) {
      return res.status(404).json({
        success: false,
        message: 'Draw not found'
      });
    }

    // Get total members count
    const totalMembers = await GroupMember.countDocuments({
      chit_id: draw.chit_group_id._id,
      status: 'active'
    });

    // Generate WhatsApp message
    const message = WhatsAppHelper.generateDrawResult(
      draw.chit_group_id,
      draw.winner_id,
      draw.prize_amount,
      draw.month,
      totalMembers
    );

    // Generate WhatsApp link (can be for winner or all members)
    const { recipientPhone } = req.body;
    const phone = recipientPhone || draw.winner_id.mobile_number;

    const whatsappUrl = WhatsAppHelper.generateShareLink(phone, message);

    // Log notification
    await Notification.create({
      type: 'draw_result',
      user_id: draw.winner_id._id,
      group_id: draw.chit_group_id._id,
      draw_id: draw._id,
      channel: 'whatsapp',
      message: message,
      status: 'sent'
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        draw: {
          month: draw.month,
          winner: draw.winner_id.full_name,
          prize: draw.prize_amount
        }
      }
    });
  } catch (error) {
    console.error('Error generating draw result share:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/group-invite
 * @desc    Generate WhatsApp share link for group invitation
 * @access  Private (Manager only)
 */
router.post('/group-invite', auth, async (req, res) => {
  try {
    const { groupId, recipientPhone } = req.body;

    if (!groupId || !recipientPhone) {
      return res.status(400).json({
        success: false,
        message: 'Group ID and recipient phone are required'
      });
    }

    // Get group
    const group = await ChitGroup.findById(groupId);

    if (!group) {
      return res.status(404).json({
        success: false,
        message: 'Group not found'
      });
    }

    // Check if user is manager of this group
    if (group.manager_id.toString() !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only group manager can send invitations'
      });
    }

    // Get manager details
    const manager = await User.findById(req.user.id);

    // Get current member count
    const currentMembers = await GroupMember.countDocuments({
      chit_id: group._id
    });

    group.current_members = currentMembers;

    // Generate WhatsApp message
    const appLink = process.env.APP_DOWNLOAD_LINK || 'Coming soon!';
    const message = WhatsAppHelper.generateGroupInvite(
      group,
      manager.full_name,
      appLink
    );

    // Generate WhatsApp link
    const whatsappUrl = WhatsAppHelper.generateShareLink(
      recipientPhone,
      message
    );

    // Log invitation
    await Notification.create({
      type: 'group_invite',
      user_id: req.user.id,
      group_id: group._id,
      channel: 'whatsapp',
      message: message,
      status: 'sent',
      metadata: {
        recipient_phone: recipientPhone
      }
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        group: {
          name: group.name,
          monthly_installment: group.monthly_installment,
          duration_months: group.duration_months
        }
      }
    });
  } catch (error) {
    console.error('Error generating group invite share:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/payment-reminder
 * @desc    Generate WhatsApp link for payment reminder (Manager)
 * @access  Private (Manager only)
 */
router.post('/payment-reminder', auth, async (req, res) => {
  try {
    const { groupId, memberId } = req.body;

    if (!groupId || !memberId) {
      return res.status(400).json({
        success: false,
        message: 'Group ID and Member ID are required'
      });
    }

    // Get group
    const group = await ChitGroup.findById(groupId);
    if (!group) {
      return res.status(404).json({
        success: false,
        message: 'Group not found'
      });
    }

    // Check authorization
    if (group.manager_id.toString() !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only group manager can send reminders'
      });
    }

    // Get member
    const member = await User.findById(memberId);
    if (!member) {
      return res.status(404).json({
        success: false,
        message: 'Member not found'
      });
    }

    // Calculate current month and due date
    const ReminderService = require('../services/reminder-service');
    const currentMonth = ReminderService.getCurrentMonthNumber(group);
    const dueDate = ReminderService.calculateDueDate(group, currentMonth);
    const daysLeft = WhatsAppHelper.getDaysUntil(dueDate.toDate());

    // Generate reminder message
    const message = WhatsAppHelper.generatePaymentReminder(
      member,
      group,
      dueDate.toDate(),
      group.monthly_installment,
      daysLeft
    );

    // Generate WhatsApp link
    const whatsappUrl = WhatsAppHelper.generateShareLink(
      member.mobile_number,
      message
    );

    // Log reminder
    await Notification.create({
      type: 'payment_reminder',
      user_id: member._id,
      group_id: group._id,
      channel: 'whatsapp',
      message: message,
      days_before_due: daysLeft,
      status: 'sent'
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        member: {
          name: member.full_name,
          mobile: member.mobile_number
        },
        payment_due: {
          amount: group.monthly_installment,
          due_date: dueDate.format('DD MMM YYYY'),
          days_left: daysLeft
        }
      }
    });
  } catch (error) {
    console.error('Error generating payment reminder:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/bulk-reminders
 * @desc    Generate bulk WhatsApp reminders for all unpaid members
 * @access  Private (Manager only)
 */
router.post('/bulk-reminders', auth, async (req, res) => {
  try {
    const { groupId } = req.body;

    if (!groupId) {
      return res.status(400).json({
        success: false,
        message: 'Group ID is required'
      });
    }

    // Get group
    const group = await ChitGroup.findById(groupId);
    if (!group) {
      return res.status(404).json({
        success: false,
        message: 'Group not found'
      });
    }

    // Check authorization
    if (group.manager_id.toString() !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only group manager can send reminders'
      });
    }

    // Get reminder service
    const ReminderService = require('../services/reminder-service');
    const currentMonth = ReminderService.getCurrentMonthNumber(group);
    const dueDate = ReminderService.calculateDueDate(group, currentMonth);
    const daysLeft = WhatsAppHelper.getDaysUntil(dueDate.toDate());

    // Get all unpaid members
    const members = await GroupMember.find({
      chit_id: group._id,
      status: 'active'
    }).populate('user_id');

    const reminders = [];

    for (const member of members) {
      // Check if paid
      const payment = await Payment.findOne({
        group_id: group._id,
        user_id: member.user_id._id,
        month: currentMonth,
        year: new Date().getFullYear(),
        status: 'success'
      });

      if (!payment) {
        // Generate reminder
        const message = WhatsAppHelper.generatePaymentReminder(
          member.user_id,
          group,
          dueDate.toDate(),
          group.monthly_installment,
          daysLeft
        );

        const whatsappUrl = WhatsAppHelper.generateShareLink(
          member.user_id.mobile_number,
          message
        );

        reminders.push({
          member: {
            id: member.user_id._id,
            name: member.user_id.full_name,
            mobile: member.user_id.mobile_number
          },
          whatsappUrl
        });

        // Log notification
        await Notification.create({
          type: 'payment_reminder',
          user_id: member.user_id._id,
          group_id: group._id,
          channel: 'whatsapp',
          message: message,
          days_before_due: daysLeft,
          status: 'sent'
        });
      }
    }

    res.json({
      success: true,
      message: `Generated ${reminders.length} reminder(s)`,
      data: {
        total_reminders: reminders.length,
        reminders: reminders
      }
    });
  } catch (error) {
    console.error('Error generating bulk reminders:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

module.exports = router;

