const express = require('express');
const router = express.Router();
const database = require('../config/database');
const { auth, isAdmin, optionalAuth } = require('../middleware/auth');

// Helper to get db instance
const getDb = () => database.db;

// ============================================
// ADVANCED QUOTE CALCULATOR
// ============================================

// POST /api/booking/calculate-quote - Calculate instant quote
router.post('/calculate-quote', optionalAuth, async (req, res) => {
  try {
    const {
      journeyType,
      pickupAddress,
      pickupPostcode,
      dropoffAddress,
      dropoffPostcode,
      pickupDate,
      pickupTime,
      passengers,
      luggage,
      returnDate,
      returnTime,
      vehicleId
    } = req.body;

    // Validate required fields
    if (!journeyType || !pickupAddress || !dropoffAddress || !pickupDate || !pickupTime || !passengers) {
      return res.status(400).json({ error: 'Missing required fields' });
    }

    // Calculate distance (simplified - in production, use Google Distance Matrix API)
    const distance = calculateDistance(pickupPostcode, dropoffPostcode);
    const estimatedTime = Math.ceil(distance / 30); // Assume 30 mph average

    // Get vehicle pricing
    let vehiclePricing;
    if (vehicleId) {
      vehiclePricing = await new Promise((resolve, reject) => {
        getDb().get('SELECT * FROM cms_vehicles WHERE id = ? AND is_active = 1', [vehicleId], (err, row) => {
          if (err) reject(err);
          else resolve(row);
        });
      });
    } else {
      // Find suitable vehicle based on passengers/luggage
      vehiclePricing = await new Promise((resolve, reject) => {
        getDb().get(
          'SELECT * FROM cms_vehicles WHERE max_passengers >= ? AND max_luggage >= ? AND is_active = 1 ORDER BY base_price ASC LIMIT 1',
          [passengers, luggage || 0],
          (err, row) => {
            if (err) reject(err);
            else resolve(row);
          }
        );
      });
    }

    if (!vehiclePricing) {
      return res.status(404).json({ error: 'No suitable vehicle found' });
    }

    // Calculate base price
    let totalPrice = parseFloat(vehiclePricing.base_price);
    let distancePrice = distance * parseFloat(vehiclePricing.price_per_mile);
    totalPrice += distancePrice;

    // Apply pricing rules
    const pricingRules = await new Promise((resolve, reject) => {
      getDb().all('SELECT * FROM cms_pricing WHERE is_active = 1', [], (err, rows) => {
        if (err) reject(err);
        else resolve(rows);
      });
    });

    let appliedRules = [];
    let discounts = 0;
    let surcharges = 0;

    // Check for return journey discount
    if (returnDate && returnTime) {
      const returnRule = pricingRules.find(r => r.applicable_to === 'return_journey' && r.rule_type === 'discount');
      if (returnRule) {
        const discount = totalPrice * (parseFloat(returnRule.value) / 100);
        discounts += discount;
        appliedRules.push({
          name: returnRule.rule_name,
          type: 'discount',
          amount: discount
        });
      }
    }

    // Check time-based surcharges
    const pickupHour = parseInt(pickupTime.split(':')[0]);
    if (pickupHour >= 0 && pickupHour < 6) {
      const surchargeRule = pricingRules.find(r => r.applicable_to === 'time_based' && r.rule_name.includes('Early'));
      if (surchargeRule) {
        const surcharge = totalPrice * (parseFloat(surchargeRule.value) / 100);
        surcharges += surcharge;
        appliedRules.push({
          name: surchargeRule.rule_name,
          type: 'surcharge',
          amount: surcharge
        });
      }
    }

    // Calculate final price
    const finalPrice = totalPrice + surcharges - discounts;

    // Return journey price if applicable
    let returnJourneyPrice = 0;
    if (returnDate && returnTime) {
      returnJourneyPrice = finalPrice; // Same price for return
    }

    res.json({
      success: true,
      quote: {
        journeyType,
        vehicle: {
          id: vehiclePricing.id,
          name: vehiclePricing.name,
          image: vehiclePricing.image_url,
          passengers: vehiclePricing.max_passengers,
          luggage: vehiclePricing.max_luggage
        },
        distance,
        estimatedTime,
        pricing: {
          basePrice: vehiclePricing.base_price,
          distancePrice,
          subtotal: totalPrice,
          discounts,
          surcharges,
          finalPrice,
          returnJourneyPrice
        },
        appliedRules,
        breakdown: {
          'Base fare': `£${vehiclePricing.base_price.toFixed(2)}`,
          'Distance charge': `£${distancePrice.toFixed(2)} (${distance} miles × £${vehiclePricing.price_per_mile})`,
          'Discounts': discounts > 0 ? `-£${discounts.toFixed(2)}` : '£0.00',
          'Surcharges': surcharges > 0 ? `+£${surcharges.toFixed(2)}` : '£0.00',
          'Total': `£${finalPrice.toFixed(2)}`
        }
      }
    });

  } catch (error) {
    console.error('Error calculating quote:', error);
    res.status(500).json({ error: 'Failed to calculate quote' });
  }
});

// GET /api/booking/vehicles/available - Get available vehicles for journey
router.get('/vehicles/available', async (req, res) => {
  try {
    const { passengers, luggage } = req.query;

    let query = 'SELECT * FROM cms_vehicles WHERE is_active = 1';
    let params = [];

    if (passengers) {
      query += ' AND max_passengers >= ?';
      params.push(parseInt(passengers));
    }

    if (luggage) {
      query += ' AND max_luggage >= ?';
      params.push(parseInt(luggage));
    }

    query += ' ORDER BY base_price ASC';

    getDb().all(query, params, (err, rows) => {
      if (err) {
        console.error('Error fetching vehicles:', err);
        return res.status(500).json({ error: 'Failed to fetch vehicles' });
      }

      const vehicles = rows.map(v => ({
        ...v,
        features: v.features ? JSON.parse(v.features) : []
      }));

      res.json({ success: true, vehicles });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// ============================================
// MANUAL QUOTE REQUESTS
// ============================================

// POST /api/quotes/request - Submit manual quote request
router.post('/request', async (req, res) => {
  try {
    const {
      name,
      email,
      phone,
      journeyType,
      pickupAddress,
      dropoffAddress,
      pickupDate,
      pickupTime,
      passengers,
      luggage,
      additionalInfo,
      returnDate,
      returnTime
    } = req.body;

    // Validate required fields
    if (!name || !email || !phone || !journeyType || !pickupAddress || !dropoffAddress || !pickupDate) {
      return res.status(400).json({ error: 'Missing required fields' });
    }

    const query = `
      INSERT INTO quote_requests (
        customer_name, customer_email, customer_phone, journey_type,
        pickup_address, dropoff_address, pickup_date, pickup_time,
        passengers, luggage, additional_info, return_date, return_time, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    `;

    getDb().run(query, [
      name, email, phone, journeyType,
      pickupAddress, dropoffAddress, pickupDate, pickupTime || '09:00',
      passengers || 1, luggage || 0, additionalInfo || '',
      returnDate || null, returnTime || null
    ], function(err) {
      if (err) {
        console.error('Error creating quote request:', err);
        return res.status(500).json({ error: 'Failed to create quote request' });
      }

      res.json({
        success: true,
        message: 'Quote request submitted successfully',
        quoteId: this.lastID
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /api/quotes/pending - Get pending quote requests (Admin only)
router.get('/pending', auth, isAdmin, async (req, res) => {
  try {
    const query = `
      SELECT * FROM quote_requests 
      WHERE status = 'pending' 
      ORDER BY created_at DESC
    `;

    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching quotes:', err);
        return res.status(500).json({ error: 'Failed to fetch quotes' });
      }

      res.json({ success: true, quotes: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /api/quotes/:id/respond - Respond to quote request (Admin only)
router.put('/:id/respond', auth, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { quote_amount, admin_notes, status } = req.body;

    const query = `
      UPDATE quote_requests 
      SET quote_amount = ?, admin_notes = ?, status = ?, responded_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    getDb().run(query, [quote_amount, admin_notes || '', status || 'quoted', id], function(err) {
      if (err) {
        console.error('Error updating quote:', err);
        return res.status(500).json({ error: 'Failed to update quote' });
      }

      if (this.changes === 0) {
        return res.status(404).json({ error: 'Quote not found' });
      }

      res.json({
        success: true,
        message: 'Quote response sent successfully'
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// ============================================
// HELPER FUNCTIONS
// ============================================

// Simplified distance calculation (replace with Google Distance Matrix API in production)
function calculateDistance(postcode1, postcode2) {
  // This is a placeholder - in production use real API
  // For demo purposes, generate a random distance between 5-50 miles
  const baseDistance = 10;
  const variation = Math.random() * 40;
  return Math.round(baseDistance + variation);
}

module.exports = router;
