const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middleware/auth');
const {
    getAllProducts,
    getProductNameById,
    createOrder,
    getOrdersByUser,
    getMessagesByUser,
    markMessagesAsRead,
    getOrderById,
    updateOrderStatus,
    createMessage,
    getMessageById
} = require('../database');
const {
    sendOrderNotificationEmail,
    sendCancellationEmail,
    sendOrderConfirmationEmail
} = require('../services/email');

// Product categories
const ALL_CATEGORIES = [
    "Winches", "Cable Drum Trailers", "Rollers", "Cable Drum Lifting Jacks", "Cable Locators", "Reeling Machine",
    "Cable Pulling Grips & Swivel Link", "Duct Rods", "Hydraulic Cutting and Crimping Tools",
    "Warning Tapes", "Manhole", "Ropes", "Duct", "Electrical", "Solar", "Pipes", "Optical Fibre Cables",
    "Optical Fiber Connectors", "Optical Fiber Adapters", "Optical Fiber Consumable",
    "Optical Fiber Instruments", "Optical Distribution Frames", "Optical Fiber Patch Cord",
    "Optical Fibre Tools", "Cabinets", "Cable Joint Products", "Cable & Wires", "Connectors",
    "Distribution Boxes", "Ducts Accessories", "Manhole Accessories", "Marking & Protection", "Earthing Hardware",
    "Miscellaneous", "Poles & Accessories", "Tapes", "Terminal Blocks", "Test & Measurement",
    "Telecom Tools", "Other Products"
];

// Helper to parse product options
function parseProduct(product) {
    let options = {};
    if (product.product_options) {
        try {
            options = JSON.parse(product.product_options);
        } catch (e) {
            options = {};
        }
    }
    return {
        id: product.id,
        name: product.product_name,
        category: product.category,
        options: options,
        rate: product.product_rate,
        stock: product.stock_status || 'out_of_stock',
        image: product.image_filename
    };
}

// Client Dashboard
router.get('/dashboard', requireAuth, (req, res) => {
    const products = getAllProducts();
    const productsList = products.map(parseProduct);

    // Group products by category
    const productsByCat = {};
    ALL_CATEGORIES.forEach(cat => {
        productsByCat[cat] = [];
    });

    productsList.forEach(product => {
        const cat = ALL_CATEGORIES.includes(product.category) ? product.category : 'Other Products';
        productsByCat[cat].push(product);
    });

    res.render('dashboard', {
        products_by_cat: productsByCat,
        all_categories: ALL_CATEGORIES
    });
});

// Place Order
router.post('/place_order', requireAuth, async (req, res) => {
    const { product_id, expected_date, quantity_value, quantity_unit, comments } = req.body;
    const userEmail = req.session.user_email;

    if (!product_id || !expected_date || !quantity_value || !quantity_unit) {
        req.flash('Missing required fields', 'danger');
        return res.redirect('/dashboard');
    }

    const productName = getProductNameById(product_id);
    if (!productName) {
        req.flash('Invalid product selected', 'danger');
        return res.redirect('/dashboard');
    }

    const quantity = `${quantity_value} ${quantity_unit}`.trim();

    // Create order
    createOrder(productName, expected_date, quantity, comments || '', userEmail);

    // Send notification to admin
    try {
        await sendOrderNotificationEmail(process.env.ADMIN_EMAIL, {
            productName,
            expectedDate: expected_date,
            quantity,
            comments: comments || '',
            userEmail
        });
        req.flash('Order placed successfully!', 'success');
    } catch (err) {
        console.error('Error sending order email:', err);
        req.flash('Order saved but email notification failed.', 'warning');
    }

    res.redirect('/dashboard');
});

// My Orders
router.get('/my-orders', requireAuth, (req, res) => {
    const orders = getOrdersByUser(req.session.user_email);
    res.render('my_orders', { orders });
});

// My Messages
router.get('/my-messages', requireAuth, (req, res) => {
    const userEmail = req.session.user_email;
    const messages = getMessagesByUser(userEmail);

    // Mark all as read
    markMessagesAsRead(userEmail);

    res.render('my_messages', { messages });
});

// Cancel Order
router.post('/cancel-order/:order_id', requireAuth, async (req, res) => {
    const orderId = req.params.order_id;
    const userEmail = req.session.user_email;

    const order = getOrderById(orderId);

    if (!order) {
        req.flash('Order not found', 'danger');
        return res.redirect('/my-messages');
    }

    if (order.user_email !== userEmail) {
        req.flash('Unauthorized action', 'danger');
        return res.redirect('/my-messages');
    }

    if (['delivered', 'dispatched', 'cancelled'].includes(order.status)) {
        req.flash(`Cannot cancel order with status: ${order.status}`, 'warning');
        return res.redirect('/my-messages');
    }

    // Update order status
    updateOrderStatus(orderId, 'cancelled');

    // Send cancellation email to admin
    try {
        await sendCancellationEmail(
            process.env.ADMIN_EMAIL,
            orderId,
            userEmail,
            order.product_name,
            order.quantity
        );
    } catch (err) {
        console.error('Failed to send cancellation email:', err);
    }

    req.flash('Order cancelled successfully. Admin has been notified.', 'success');
    res.redirect('/my-messages');
});

// Finalize/Confirm Order
router.get('/place-order/:order_id', requireAuth, async (req, res) => {
    const orderId = req.params.order_id;
    const userEmail = req.session.user_email;

    const order = getOrderById(orderId);

    if (!order) {
        req.flash('Order not found', 'danger');
        return res.redirect('/my-messages');
    }

    if (order.user_email !== userEmail) {
        req.flash('Unauthorized action', 'danger');
        return res.redirect('/my-messages');
    }

    if (!['quote sent', 'inquiry received'].includes(order.status)) {
        req.flash(`Cannot confirm order with current status: ${order.status}`, 'warning');
        return res.redirect('/my-messages');
    }

    // Update order status
    updateOrderStatus(orderId, 'order placed');

    // Send confirmation email to admin
    try {
        await sendOrderConfirmationEmail(
            process.env.ADMIN_EMAIL,
            orderId,
            userEmail,
            order.product_name,
            order.quantity
        );
    } catch (err) {
        console.error('Failed to send confirmation email:', err);
    }

    // Create message for client
    createMessage(
        orderId,
        userEmail,
        `Order Confirmed - #${orderId}`,
        `Your order for '${order.product_name}' (${order.quantity}) has been confirmed successfully. The admin has been notified and will process your order soon.`,
        null,
        order.product_name,
        order.quantity
    );

    req.flash('Order confirmed successfully! Admin has been notified.', 'success');
    res.redirect('/my-messages');
});

// Contact Us (WhatsApp redirect)
router.get('/contact-us', (req, res) => {
    const adminWhatsApp = process.env.ADMIN_WHATSAPP || '';
    const waLink = `https://web.whatsapp.com/send?phone=${adminWhatsApp}`;
    res.redirect(waLink);
});

// Talk Further (WhatsApp with order context)
router.get('/talk-further/:message_id', requireAuth, (req, res) => {
    const messageId = req.params.message_id;
    const message = getMessageById(messageId);

    if (!message) {
        req.flash('Message not found');
        return res.redirect('/my-messages');
    }

    const adminWhatsApp = process.env.ADMIN_WHATSAPP || '';
    const text = `Hello Admin, I want to discuss further about my PLACED ORDER.\n\nOrder ID: ${message.order_id}\nOrder: ${message.order_name} (${message.order_quantity})\nMy Email: ${message.user_email}`;
    const encodedText = encodeURIComponent(text);
    const waLink = `https://web.whatsapp.com/send?phone=${adminWhatsApp}&text=${encodedText}`;

    res.redirect(waLink);
});

module.exports = router;
