const express = require('express');
const router = express.Router();
const { supabaseAdmin } = require('../config/supabase');
const { authenticateUser, requireRole } = require('../middleware/auth');
const { validateRequest, schemas } = require('../middleware/validation');
const { v4: uuidv4 } = require('uuid');

// Generate unique order number
function generateOrderNumber() {
    const timestamp = Date.now().toString().slice(-6);
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `ORD${timestamp}${random}`;
}

// Create new order
router.post('/', authenticateUser, validateRequest(schemas.createOrder), async (req, res) => {
    try {
        const { items, payment_method, payment_details } = req.body;
        const userId = req.user.id;

        // Get user details
        const { data: user } = await supabaseAdmin
            .from('users')
            .select('*')
            .eq('id', userId)
            .single();

        if (!user) {
            return res.status(404).json({ error: 'User not found' });
        }

        // Calculate total and estimated time
        let total = 0;
        let maxPrepTime = 0;
        const orderItems = [];

        for (const item of items) {
            const { data: foodItem } = await supabaseAdmin
                .from('food_items')
                .select('*')
                .eq('id', item.food_id)
                .single();

            if (!foodItem) {
                return res.status(404).json({ error: `Food item ${item.food_id} not found` });
            }

            if (foodItem.availability !== 'available') {
                return res.status(400).json({ error: `${foodItem.name} is not available` });
            }

            const itemTotal = foodItem.price * item.quantity;
            total += itemTotal;
            maxPrepTime = Math.max(maxPrepTime, foodItem.prep_time);

            orderItems.push({
                food_id: item.food_id,
                quantity: item.quantity,
                price: foodItem.price
            });
        }

        // Create order
        const orderNumber = generateOrderNumber();
        const { data: order, error: orderError } = await supabaseAdmin
            .from('orders')
            .insert({
                order_number: orderNumber,
                student_id: userId,
                status: 'ordered',
                total,
                payment_method,
                estimated_time: maxPrepTime
            })
            .select()
            .single();

        if (orderError) throw orderError;

        // Create order items
        const orderItemsWithOrderId = orderItems.map(item => ({
            ...item,
            order_id: order.id
        }));

        const { error: itemsError } = await supabaseAdmin
            .from('order_items')
            .insert(orderItemsWithOrderId);

        if (itemsError) throw itemsError;

        // Save payment details if provided
        if (payment_details) {
            await supabaseAdmin
                .from('payments')
                .upsert({
                    student_id: userId,
                    payment_method,
                    name: payment_details.name,
                    mobile: payment_details.mobile,
                    upi_id: payment_details.upi_id,
                    card_last4: payment_details.card_last4,
                    is_default: true
                });
        }

        // Create notification
        await supabaseAdmin
            .from('notifications')
            .insert({
                user_id: userId,
                order_id: order.id,
                message: `Order ${orderNumber} placed successfully! Estimated time: ${maxPrepTime} minutes`
            });

        // Fetch complete order with items
        const { data: completeOrder } = await supabaseAdmin
            .from('orders')
            .select(`
        *,
        order_items (
          *,
          food_items (*)
        )
      `)
            .eq('id', order.id)
            .single();

        res.json({
            success: true,
            order: completeOrder
        });
    } catch (error) {
        console.error('Create order error:', error);
        res.status(500).json({ error: 'Failed to create order', details: error.message });
    }
});

// Get user's orders
router.get('/my-orders', authenticateUser, async (req, res) => {
    try {
        const userId = req.user.id;
        const { status } = req.query;

        let query = supabaseAdmin
            .from('orders')
            .select(`
        *,
        order_items (
          *,
          food_items (*)
        )
      `)
            .eq('student_id', userId);

        if (status) {
            query = query.eq('status', status);
        }

        query = query.order('created_at', { ascending: false });

        const { data, error } = await query;

        if (error) throw error;

        res.json({ success: true, orders: data });
    } catch (error) {
        console.error('Get orders error:', error);
        res.status(500).json({ error: 'Failed to fetch orders' });
    }
});

// Get all orders (kitchen/admin only)
router.get('/', authenticateUser, requireRole('kitchen', 'admin'), async (req, res) => {
    try {
        const { status, date } = req.query;

        let query = supabaseAdmin
            .from('orders')
            .select(`
        *,
        users (student_id, name),
        order_items (
          *,
          food_items (*)
        )
      `);

        if (status) {
            query = query.eq('status', status);
        }

        if (date) {
            const startOfDay = new Date(date);
            startOfDay.setHours(0, 0, 0, 0);
            const endOfDay = new Date(date);
            endOfDay.setHours(23, 59, 59, 999);

            query = query
                .gte('created_at', startOfDay.toISOString())
                .lte('created_at', endOfDay.toISOString());
        }

        query = query.order('created_at', { ascending: false });

        const { data, error } = await query;

        if (error) throw error;

        res.json({ success: true, orders: data });
    } catch (error) {
        console.error('Get all orders error:', error);
        res.status(500).json({ error: 'Failed to fetch orders' });
    }
});

// Get single order
router.get('/:id', authenticateUser, async (req, res) => {
    try {
        const { data, error } = await supabaseAdmin
            .from('orders')
            .select(`
        *,
        users (student_id, name),
        order_items (
          *,
          food_items (*)
        )
      `)
            .eq('id', req.params.id)
            .single();

        if (error) throw error;

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

        // Check if user has permission to view this order
        if (req.userRole !== 'kitchen' && req.userRole !== 'admin' && data.student_id !== req.user.id) {
            return res.status(403).json({ error: 'Access denied' });
        }

        res.json({ success: true, order: data });
    } catch (error) {
        console.error('Get order error:', error);
        res.status(500).json({ error: 'Failed to fetch order' });
    }
});

// Update order status (kitchen/admin only)
router.patch('/:id/status', authenticateUser, requireRole('kitchen', 'admin'), async (req, res) => {
    try {
        const { status } = req.body;
        const orderId = req.params.id;

        if (!['ordered', 'preparing', 'ready', 'completed', 'cancelled'].includes(status)) {
            return res.status(400).json({ error: 'Invalid status' });
        }

        // Get order details
        const { data: order } = await supabaseAdmin
            .from('orders')
            .select('*, users(id)')
            .eq('id', orderId)
            .single();

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

        // Update order status
        const { data, error } = await supabaseAdmin
            .from('orders')
            .update({ status, updated_at: new Date().toISOString() })
            .eq('id', orderId)
            .select()
            .single();

        if (error) throw error;

        // Create notification for status change
        let message = '';
        if (status === 'preparing') {
            message = `Your order ${order.order_number} is being prepared`;
        } else if (status === 'ready') {
            message = `Your order ${order.order_number} is ready for pickup!`;
        } else if (status === 'completed') {
            message = `Order ${order.order_number} completed. Thank you!`;
        } else if (status === 'cancelled') {
            message = `Order ${order.order_number} has been cancelled`;
        }

        if (message) {
            await supabaseAdmin
                .from('notifications')
                .insert({
                    user_id: order.student_id,
                    order_id: orderId,
                    message
                });
        }

        res.json({ success: true, order: data });
    } catch (error) {
        console.error('Update order status error:', error);
        res.status(500).json({ error: 'Failed to update order status' });
    }
});

// Get order analytics (kitchen/admin only)
router.get('/analytics/summary', authenticateUser, requireRole('kitchen', 'admin'), async (req, res) => {
    try {
        const { date } = req.query;
        const today = date ? new Date(date) : new Date();
        today.setHours(0, 0, 0, 0);
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);

        // Get today's orders
        const { data: orders } = await supabaseAdmin
            .from('orders')
            .select('*, order_items(*)')
            .gte('created_at', today.toISOString())
            .lt('created_at', tomorrow.toISOString());

        const totalOrders = orders?.length || 0;
        const totalRevenue = orders?.reduce((sum, order) => sum + parseFloat(order.total), 0) || 0;
        const averagePrepTime = orders?.reduce((sum, order) => sum + (order.estimated_time || 0), 0) / totalOrders || 0;

        // Count by status
        const statusCounts = {
            ordered: 0,
            preparing: 0,
            ready: 0,
            completed: 0,
            cancelled: 0
        };

        orders?.forEach(order => {
            statusCounts[order.status] = (statusCounts[order.status] || 0) + 1;
        });

        res.json({
            success: true,
            analytics: {
                total_orders: totalOrders,
                total_revenue: totalRevenue.toFixed(2),
                average_prep_time: Math.round(averagePrepTime),
                status_counts: statusCounts,
                date: today.toISOString().split('T')[0]
            }
        });
    } catch (error) {
        console.error('Get analytics error:', error);
        res.status(500).json({ error: 'Failed to fetch analytics' });
    }
});

module.exports = router;
