// controllers/workOrderController.js
const WorkOrder = require('../models/WorkOrder');
const Labour = require('../models/Labour');
const Customer = require('../models/Customer');
const paymentController = require('./paymentController');
const { generateEmailHTML } = require('../utils/emailTemplates');

require('dotenv').config();
const emailService = require('../utils/emailService');

exports.requestWork = async (req, res) => {
    try {
        const {
            laborerId,
            customerName,
            customerPhone,
            customerEmail,
            workDescription,
            customerLocation,
            requiredLaborType
        } = req.body;

        const requestExpiresAt = new Date(Date.now() + 3 * 60 * 1000); // 3 minutes

        const newWorkOrder = new WorkOrder({
            labourerId: laborerId,
            customerId: req.user._id,
            customerName,
            customerPhone,
            customerEmail,
            workDescription,
            customerLocation,
            requiredLaborType,
            status: 'pending',
            requestExpiresAt
        });

        const savedOrder = await newWorkOrder.save();

        await Labour.findByIdAndUpdate(laborerId, {
            $push: { pendingWorkOrders: savedOrder._id }
        });

        // --- Your existing Socket.IO notifications (no changes needed) ---
        const io = req.app.get('io');
        io.to(`laborer_${laborerId}`).emit('newOrderRequest', { order: savedOrder, message: 'You have a new work request!' });
        io.to(`customer_${req.user._id}`).emit('orderRequestSent', { order: savedOrder, message: 'Your work request has been sent.' });
        
        // --- MODIFIED: Use stylish email template for notifications ---
        try {
            // Find the labourer to get their details
            const labourer = await Labour.findById(laborerId).select('email name');

            // 1. Email to the Labourer
            if (labourer && labourer.email) {
                const labourerEmailInfo = {
                    title: 'You Have a New Work Request!',
                    name: labourer.name,
                    message: `You have received a new work request from <strong>${customerName}</strong> for "<strong>${workDescription}</strong>".<br><br>Please log in to your laborPK account to review and respond. This request will expire soon.`
                    // Optional button:
                    // buttonUrl: `${process.env.FRONTEND_URL}/dashboard/orders`,
                    // buttonText: 'View Request'
                };
                await emailService.sendEmail({
                    to: labourer.email,
                    subject: 'New Work Request Received!',
                    html: generateEmailHTML(labourerEmailInfo)
                });
            }

            // 2. Email to the Customer
            if (customerEmail) {
                const customerEmailInfo = {
                    title: 'Your Work Request is Sent!',
                    name: customerName,
                    message: `Your work request for "<strong>${workDescription}</strong>" has been successfully sent to the labourer. You will be notified as soon as they respond.`
                };
                await emailService.sendEmail({
                    to: customerEmail,
                    subject: 'Your Work Request Has Been Sent',
                    html: generateEmailHTML(customerEmailInfo)
                });
            }
        } catch (emailError) {
            console.error("Failed to send email notifications for new order:", savedOrder._id, emailError);
        }
        // --- END MODIFICATION ---

        res.status(201).json({
            message: 'Work request sent successfully. The labourer has 3 minutes to respond.',
            order: savedOrder
        });

    } catch (err) {
        console.error('Error creating work order:', err);
        res.status(500).json({ message: 'Failed to send work request', error: err.message });
    }
};

exports.getLabourerOrders = async (req, res) => {
    try {
        // Get labourerId from authenticated user (since labour is logged in)
        const labourerId = req.labour._id; // Changed from params to authenticated user

        // Fetch orders and filter out expired pending ones
        const orders = await WorkOrder.find({
            labourerId,
            $or: [
                { status: { $ne: 'pending' } },
                {
                    status: 'pending',
                    requestExpiresAt: { $gt: new Date() }
                }
            ]
        })
        .populate('customerId', 'name phone email') // Populate customer info
        .sort({ createdAt: -1 });

        res.json(orders);
    } catch (err) {
        console.error('Error fetching labourer orders:', err);
        res.status(500).json({ message: 'Failed to fetch orders', error: err.message });
    }
};


exports.updateOrderStatus = async (req, res) => {
    try {
        const { orderId } = req.params;
        const { status } = req.body;

        // --- MODIFIED: Populate customer and labourer info to get their details ---
        const order = await WorkOrder.findById(orderId)
            .populate('customerId', 'name email')
            .populate('labourerId', 'name email');

        if (!order) {
            return res.status(404).json({ message: 'Order not found' });
        }

        if (order.status === 'pending' && order.requestExpiresAt < new Date()) {
            return res.status(403).json({ message: 'This work request has expired.' });
        }

        const originalStatus = order.status;
        order.status = status;

        // --- Simplified logic for status update, as your previous logic was already good ---
        if (status === 'accepted' && originalStatus !== 'accepted') {
            const paymentResult = await paymentController.recordLabourerAcceptanceFee(
                order.labourerId._id, order._id, 100
            );
            if (!paymentResult.success) console.error(`Payment failed for order ${orderId}`);
        }

        await order.save();
        
        // Clean up pending orders if accepted/rejected
        if (status === 'accepted' || status === 'rejected') {
            await Labour.findByIdAndUpdate(order.labourerId._id, {
                $pull: { pendingWorkOrders: orderId }
            });
        }
        
        // --- NEW: Email Notification Logic ---
        try {
            let customerEmailInfo = { title: '', message: '' };
            let labourerEmailInfo = { title: '', message: '' };

            switch (status) {
                case 'accepted':
                    customerEmailInfo = {
                        title: 'Your Work Order is Accepted!',
                        message: `Great news! Your work order for "<strong>${order.workDescription}</strong>" has been accepted by the labourer, <strong>${order.labourerId.name}</strong>. They will be in touch with you shortly.`
                    };
                    labourerEmailInfo = {
                        title: 'Work Order Accepted!',
                        message: `You have successfully accepted the work order from <strong>${order.customerId.name}</strong>. Please coordinate with the customer to begin the work.`
                    };
                    break;
                case 'rejected':
                    customerEmailInfo = {
                        title: 'Work Order Update',
                        message: `Unfortunately, the work order for "<strong>${order.workDescription}</strong>" was rejected by the labourer. You can search for and request another labourer at any time.`
                    };
                    labourerEmailInfo = {
                        title: 'Work Order Rejected',
                        message: `You have rejected the work order from <strong>${order.customerId.name}</strong>. No further action is needed.`
                    };
                    break;
                case 'completed':
                    customerEmailInfo = {
                        title: 'Your Work Order is Complete!',
                        message: `The work order "<strong>${order.workDescription}</strong>" has been marked as complete by <strong>${order.labourerId.name}</strong>. We hope you had a great experience! Please consider leaving a review to help others.`
                        // You can add a button to the review page
                        // buttonUrl: `${process.env.FRONTEND_URL}/orders/${order._id}/review`,
                        // buttonText: 'Leave a Review'
                    };
                    labourerEmailInfo = {
                        title: 'Work Order Completed!',
                        message: `You have successfully marked the order from <strong>${order.customerId.name}</strong> as complete. Well done!`
                    };
                    break;
            }
            
            // Send emails if the status is one we handle
            if (customerEmailInfo.title && order.customerId.email) {
                await emailService.sendEmail({
                    to: order.customerId.email,
                    subject: customerEmailInfo.title,
                    html: generateEmailHTML({ ...customerEmailInfo, name: order.customerId.name })
                });
            }
            if (labourerEmailInfo.title && order.labourerId.email) {
                 await emailService.sendEmail({
                    to: order.labourerId.email,
                    subject: labourerEmailInfo.title,
                    html: generateEmailHTML({ ...labourerEmailInfo, name: order.labourerId.name })
                });
            }
        } catch (emailError) {
             console.error('Failed to send status update email:', emailError);
        }
        // --- END Email Notification Logic ---
        
        // --- Your existing Socket.IO notifications (no changes needed here) ---
        const io = req.app.get('io');
        io.to(`customer_${order.customerId._id}`).emit('orderStatusUpdate', { orderId, status, message: `Your order status changed to ${status}.` });
        io.to(`laborer_${order.labourerId._id}`).emit('orderStatusUpdate', { orderId, status, message: `Order status changed to ${status}.` });
        if (status === 'accepted') io.emit('orderTaken', { orderId });
        
        res.json({ message: 'Order status updated successfully', order });

    } catch (err) {
        console.error('Error updating order status:', err);
        res.status(500).json({ message: 'Failed to update order status', error: err.message });
    }
};

exports.addReview = async (req, res) => {
    try {
        const { orderId } = req.params;
        const { rating, reviewComment } = req.body;

        // Validate input
        if (!rating || rating < 1 || rating > 5) {
            return res.status(400).json({ message: 'Please provide a valid rating (1-5)' });
        }
        if (!reviewComment || reviewComment.trim() === '') {
            return res.status(400).json({ message: 'Please provide a review comment' });
        }

        const order = await WorkOrder.findById(orderId);

        if (!order) {
            return res.status(404).json({ message: 'Order not found' });
        }

        // Only allow reviews for completed orders
        if (order.status !== 'completed') {
            return res.status(400).json({ message: 'Reviews can only be added to completed orders' });
        }

        // Update the review
        order.rating = rating;
        order.reviewComment = reviewComment;
        await order.save();

        // --- REAL-TIME ADDITION: Notify Labourer of new review (optional) ---
        const io = req.app.get('io');
        io.to(`laborer_${order.labourerId}`).emit('newReview', {
            orderId: order._id,
            rating: rating,
            reviewComment: reviewComment,
            message: 'You have received a new review!'
        });
        console.log(`Emitted 'newReview' to laborer_${order.labourerId} for order ${order._id}`);
        // --- END REAL-TIME ADDITION ---

        res.json({
            message: 'Review added successfully',
            order
        });
    } catch (err) {
        console.error('Error adding review:', err);
        res.status(500).json({
            message: 'Failed to add review',
            error: err.message
        });
    }
};

exports.getCustomerOrders = async (req, res) => {
    try {
        const customerId = req.user._id;

        const orders = await WorkOrder.find({ customerId: customerId })
                                     .populate('labourerId')
                                     .sort({ createdAt: -1 });

        // --- REAL-TIME ADDITION: Emit initial customer orders via Socket.IO ---
        const io = req.app.get('io'); // Get the Socket.IO instance
        io.to(`customer_${customerId}`).emit('initialCustomerOrders', {
            orders: orders,
            message: 'Your initial order list has been loaded.'
        });
        console.log(`Emitted 'initialCustomerOrders' to customer_${customerId}`);
        // --- END REAL-TIME ADDITION ---

        res.json(orders); // Still send the HTTP response
    } catch (err) {
        console.error('Error fetching customer orders:', err);
        res.status(500).json({ message: 'Failed to fetch your work orders', error: err.message });
    }
};
