/*
 Consolidated Customer delivery manager.
 Responsibilities:
 - Create delivery modal and submit to API
 - Price calculation via api/deliveries/price.php
 - Detect user location via Geolocation + Nominatim reverse geocoding
 - Load list of deliveries and render history
 - Show tracking modal with timeline by calling api/deliveries/track.php
*/

class CustomerManager {
    constructor(app) {
        this.app = app;
        this.priceUpdateTimeout = null;
        this.init();
    }

    init() {
        this.setupListeners();
        // If a deliveries list container exists on load, fetch deliveries
        document.addEventListener('DOMContentLoaded', () => this.loadDeliveries());
    }

    setupListeners() {
        // Delegated click handlers for action-cards and track buttons
        document.addEventListener('click', (e) => {
            const trackBtn = e.target.closest('.track-btn');

            // This listener remains for track buttons on the orders/deliveries list
            if (trackBtn) this.showTrackingModal(trackBtn.dataset.id);
        });

        // Handle delivery form input changes (price recalculation)
        document.addEventListener('input', (e) => {
            if (!e.target.closest) return;
            const form = e.target.closest('#delivery-form');
            if (form && ['pickup_location', 'delivery_location', 'package_weight', 'delivery_mode'].includes(e.target.name)) {
                // Debounce price update
                clearTimeout(this.priceUpdateTimeout);
                this.priceUpdateTimeout = setTimeout(() => {
                    this.updateDeliveryPrice(form);
                }, 500); // Wait 500ms after user stops typing
            }
        });
    }

    async promptTrack() {
        const trackingNumber = await this.app.showPrompt('Enter your tracking number:', 'e.g. MBX12345678', 'Track Package');
        if (trackingNumber) {
            // try to fetch by tracking number
            this.fetchTrackingByNumber(trackingNumber);
        }
    }

    async fetchTrackingByNumber(trackingNumber) {
        try {
            const res = await fetch(`api/deliveries/track.php?tracking=${encodeURIComponent(trackingNumber)}`);
            const data = await res.json();
            if (data.success) {
                this.showTrackingModal(data.delivery.id);
            } else {
                this.app.notifier.show(data.message || 'Tracking not found', 'error');
            }
        } catch (err) {
            console.error(err);
            this.app.notifier.show('Could not fetch tracking information', 'error');
        }
    }

    showDeliveryModal() {
        const user = this.app?.currentUser;
        if (!user) {
            this.app.notifier.show('Please log in to create a delivery', 'warning');
            if (this.app?.showLoginForm) {
                this.app.showLoginForm();
            } else {
                window.location.href = '/?page=login';
            }
            return;
        }

        const modalContent = `
            <form id="delivery-form">
                <div class="delivery-sections">
                    <div class="delivery-section">
                        <h4><i class="fas fa-shipping-fast"></i> Delivery Mode</h4>
                        <div class="form-group radio-group">
                            <label class="radio-label">
                                <input type="radio" name="delivery_mode" value="standard" checked> Standard
                            </label>
                            <label class="radio-label">
                                <input type="radio" name="delivery_mode" value="express"> Express
                            </label>
                        </div>
                    </div>
                    <div class="delivery-section">
                        <h4><i class="fas fa-box"></i> Package Details</h4>
                        <div class="form-group">
                            <label for="package_description">What are you sending?</label>
                            <textarea id="package_description" name="package_description" rows="2" required></textarea>
                        </div>
                        <div class="form-group">
                            <label for="package_weight">Weight (kg)</label>
                            <input id="package_weight" name="package_weight" type="number" step="0.1" min="0.1" value="1.0" required>
                        </div>
                        <div class="form-group">
                            <label for="package_value">Value ($, optional)</label>
                            <input id="package_value" name="package_value" type="number" step="0.01" min="0">
                        </div>
                    </div>

                    <div class="delivery-section">
                        <h4><i class="fas fa-map-marker-alt"></i> Pickup & Dropoff</h4>
                        <div class="form-group">
                            <label for="pickup_location">Pickup Location</label>
                            <select class="saved-address-select" data-target="pickup_location">
                                <option value="">-- Select a saved address --</option>
                            </select>
                            <div class="location-input-group">
                                <input id="pickup_location" name="pickup_location" type="text" placeholder="Or enter pickup address manually" required>
                                <button type="button" class="location-btn" data-target="pickup_location" title="Detect location"><i class="fas fa-crosshairs"></i></button>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="delivery_location">Delivery Location</label>
                            <select class="saved-address-select" data-target="delivery_location">
                                <option value="">-- Select a saved address --</option>
                            </select>
                            <div class="location-input-group">
                                <input id="delivery_location" name="delivery_location" type="text" placeholder="Or enter delivery address manually" required>
                                <button type="button" class="location-btn" data-target="delivery_location" title="Detect location"><i class="fas fa-crosshairs"></i></button>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="delivery_instructions">Special instructions</label>
                            <textarea id="delivery_instructions" name="delivery_instructions" rows="2"></textarea>
                        </div>
                    </div>

                    <div class="delivery-section pricing-section">
                        <h4><i class="fas fa-receipt"></i> Price Summary</h4>
                        <div class="price-breakdown">
                            <div class="price-item"><span>Base:</span><span class="base-fee">$0.00</span></div>
                            <div class="price-item"><span>Distance:</span><span class="distance-fee">Calculating...</span></div>
                            <div class="price-item"><span>Weight:</span><span class="weight-fee">$0.00</span></div>
                            <div class="price-item discount-item" style="display: none;"><span>Discount:</span><span class="discount-fee">-$0.00</span></div>
                            <div class="price-item total"><span>Total:</span><span class="total-price">Calculating...</span></div>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="button" class="btn-secondary" data-action="cancel">Cancel</button>
                    <button type="submit" class="btn-primary">Create Delivery</button>
                </div>
            </form>
        `;

        const modalInstance = new Modal({ title: 'Create Delivery', content: modalContent, size: 'large-modal' });
        const modal = modalInstance.show();

        // attach handlers
        modal.addEventListener('click', (ev) => {
            if (ev.target.dataset.action === 'cancel') {
                modalInstance.close();
            }
            // location detect
            if (ev.target.closest('.location-btn')) {
                const target = ev.target.closest('.location-btn').dataset.target;
                this.detectLocation(target);
            }
        });

        modal.addEventListener('change', (e) => {
            if (e.target.classList.contains('saved-address-select')) {
                const targetInputId = e.target.dataset.target;
                const targetInput = document.getElementById(targetInputId);
                if (targetInput) targetInput.value = e.target.value;
            }
        });

        const form = document.getElementById('delivery-form');
        form.addEventListener('submit', async (ev) => {
            ev.preventDefault();
            await this.createDelivery(form, modalInstance);
        });

        // initial price calculation
        this.populateSavedAddresses(modal);
        this.updateDeliveryPrice(form);
    }

    async populateSavedAddresses(modal) {
        try {
            const response = await fetch('api/users/addresses.php');
            const data = await response.json();
            if (data.success && data.addresses.length > 0) {
                const optionsHTML = data.addresses.map(addr =>
                    `<option value="${addr.address}">${addr.label} - ${this.truncate(addr.address, 40)}</option>`
                ).join('');

                modal.querySelectorAll('.saved-address-select').forEach(select => {
                    select.insertAdjacentHTML('beforeend', optionsHTML);
                });
            }
        } catch (error) {
            console.warn('Could not load saved addresses for delivery modal.', error);
        }
    }

    async detectLocation(targetId) {
        const input = document.getElementById(targetId);
        if (!input) return;

        try {
            const pos = await this.getCurrentPosition();
            const addr = await this.getLocationAddress(pos.coords.latitude, pos.coords.longitude);
            input.value = addr || `${pos.coords.latitude}, ${pos.coords.longitude}`;
            // trigger price update
            const form = input.closest('#delivery-form');
            if (form) this.updateDeliveryPrice(form);
        } catch (err) {
            console.error('Location detect failed', err);
            this.app.notifier.show('Could not detect location. Please enter it manually.', 'error');
        }
    }

    getCurrentPosition() {
        return new Promise((resolve, reject) => {
            if (!navigator.geolocation) return reject(new Error('Geolocation not supported'));
            navigator.geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy: true, timeout: 8000 });
        });
    }

    async getLocationAddress(lat, lon) {
        try {
            const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json`);
            const data = await res.json();
            return data.display_name;
        } catch (err) {
            console.warn('Reverse geocode failed', err);
            return null;
        }
    }

    async updateDeliveryPrice(form) {
        const formData = new FormData(form);
        // Basic client validation
        const pickup = formData.get('pickup_location');
        const delivery = formData.get('delivery_location');
        const weight = parseFloat(formData.get('package_weight') || '0') || 0;

        // only query if we have values
        if (!pickup || !delivery || weight <= 0) return;

        try {
            const res = await fetch('api/deliveries/price.php', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.success && data.pricing) {
                const pricing = data.pricing;
                const container = form.querySelector('.price-breakdown');
                if (container) {
                    container.querySelector('.base-fee').textContent = `$${(pricing.base || 0).toFixed(2)}`;
                    container.querySelector('.distance-fee').textContent = `$${(pricing.distance || 0).toFixed(2)}`;
                    container.querySelector('.weight-fee').textContent = `$${(pricing.weight || 0).toFixed(2)}`;
                    container.querySelector('.total-price').textContent = `$${(pricing.total || 0).toFixed(2)}`;

                    const discountItem = container.querySelector('.discount-item');
                    const discountFee = container.querySelector('.discount-fee');
                    if (pricing.is_discounted) {
                        discountItem.style.display = 'flex';
                        discountFee.textContent = `-$${(pricing.discount || 0).toFixed(2)}`;
                        this.app.notifier.show(`Congrats! You've earned a ${this.app.settings.loyalty_delivery_discount_percent}% discount on this delivery!`, 'success');
                    } else {
                        discountItem.style.display = 'none';
                    }
                }
            } else {
                // Handle case where pricing API fails
            }
        } catch (err) {
            console.error('Price update failed', err);
        }
    }

    async createDelivery(form, modalInstance) {
        const submitBtn = form.querySelector('button[type="submit"]');
        try {
            submitBtn.disabled = true;
            submitBtn.textContent = 'Creating...';

            const formData = new FormData(form);
            const deliveryData = {
                package_description: formData.get('package_description'),
                package_weight: parseFloat(formData.get('package_weight')),
                package_value: parseFloat(formData.get('package_value')) || 0,
                pickup_location: formData.get('pickup_location'),
                delivery_location: formData.get('delivery_location'),
                delivery_instructions: formData.get('delivery_instructions'),
                delivery_mode: formData.get('delivery_mode')
            };

            const res = await fetch('api/deliveries/create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(deliveryData)
            });
            const data = await res.json();
            if (data.success) {
                this.app.notifier.show('Delivery created successfully!', 'success');
                modalInstance.close();
                this.loadDeliveries();
            } else {
                this.app.notifier.show(data.message || 'Could not create delivery', 'error');
            }
        } catch (err) {
            console.error('Create delivery error', err);
            this.app.notifier.show('Failed to create delivery', 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = 'Create Delivery';
        }
    }

    async loadDeliveries(showModalIfEmpty = false) {
        const container = document.querySelector('.deliveries-list');
        if (!container) return;

        container.innerHTML = '<div class="empty-state"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';

        try {
            const res = await fetch('api/deliveries/list.php');
            const data = await res.json();
            if (data.success) {
                const deliveries = data.deliveries || [];
                if (deliveries.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-box-open"></i>
                            <h3>No Deliveries</h3>
                            <p>Create a delivery to get started</p>
                            <button class="btn btn-primary action-create-delivery">Create Delivery</button>
                        </div>
                    `;
                    container.querySelector('.action-create-delivery')?.addEventListener('click', () => this.showDeliveryModal());
                    return;
                }

                container.innerHTML = deliveries.map(d => this.deliveryItemHTML(d)).join('');
                // The delegated listener in setupListeners covers these dynamically added track buttons
            } else {
                container.innerHTML = '<div class="alert alert-danger">Could not load deliveries</div>';
            }
        } catch (err) {
            console.error('Load deliveries failed', err);
            container.innerHTML = '<div class="alert alert-danger">Error loading deliveries</div>';
        }
    }

    deliveryItemHTML(d) {
        const statusText = this.getStatusText(d.status);
        const statusClass = this.getStatusClass(d.status);
        return `
            <div class="delivery-item">
                <div>
                    <h4>#${d.tracking_id}</h4>
                    <div class="delivery-meta">
                        <span><i class="fas fa-map-marker-alt"></i> ${this.truncate(d.pickup_location, 40)}</span>
                        <span><i class="fas fa-arrow-right"></i></span>
                        <span><i class="fas fa-map-marker-alt"></i> ${this.truncate(d.delivery_location, 40)}</span>
                    </div>
                </div>
                <div class="delivery-status">
                    <span class="status-text ${statusClass}">${statusText}</span>
                    <button class="btn btn-sm btn-primary track-btn" data-id="${d.id}"><i class="fas fa-route"></i> Track</button>
                </div>
            </div>
        `;
    }

    truncate(str, len) {
        if (!str) return '';
        return str.length > len ? str.slice(0, len - 3) + '...' : str;
    }

    getStatusText(status) {
        return {
            pending: 'Awaiting Rider',
            accepted: 'Rider Assigned',
            picked_up: 'Picked Up',
            in_transit: 'In Transit',
            delivered: 'Delivered',
            cancelled: 'Cancelled'
        }[status] || 'Unknown';
    }

    getStatusClass(status) {
        return {
            pending: 'text-warning',
            accepted: 'text-primary',
            picked_up: 'text-info',
            in_transit: 'text-primary',
            delivered: 'text-success',
            cancelled: 'text-danger'
        }[status] || 'text-secondary';
    }

    async showTrackingModal(deliveryId) {
        const modalContent = `<div class="tracking-info"><div class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</div></div>`;

        const modalInstance = new Modal({
            title: `Tracking Delivery #${deliveryId}`,
            content: modalContent,
            size: 'large-modal'
        });

        const modal = modalInstance.show();

        try {
            const res = await fetch(`api/deliveries/track.php?id=${encodeURIComponent(deliveryId)}`);
            const data = await res.json();
            const container = modal.querySelector('.tracking-info');
            if (data.success && data.delivery) {
                container.innerHTML = this.renderTrackingHTML(data.delivery);
            } else {
                container.innerHTML = `<div class="alert alert-danger">${data.message || 'Could not load tracking'}</div>`;
            }
        } catch (err) {
            console.error('Tracking fetch failed', err);
            modal.querySelector('.tracking-info').innerHTML = '<div class="alert alert-danger">Error loading tracking</div>';
        }
    }

    renderTrackingHTML(delivery) {
        const statuses = [
            { key: 'pending', title: 'Order Placed', desc: 'Your delivery request has been received' },
            { key: 'accepted', title: 'Rider Assigned', desc: 'A rider has been assigned' },
            { key: 'picked_up', title: 'Picked Up', desc: 'Package picked up by rider' },
            { key: 'in_transit', title: 'In Transit', desc: 'Package is on the way' },
            { key: 'delivered', title: 'Delivered', desc: 'Package delivered' }
        ];

        const currentIndex = statuses.findIndex(s => s.key === delivery.status);

        return `
            <div class="tracking-status">
                <div class="current-status"><i class="fas ${delivery.status === 'delivered' ? 'fa-check-circle' : 'fa-truck'}"></i> ${this.getStatusText(delivery.status)}</div>
                <div class="status-time">Last updated: ${new Date(delivery.updated_at).toLocaleString()}</div>
            </div>
            <div class="tracking-timeline">
                ${statuses.map((s, idx) => `
                    <div class="timeline-item ${idx < currentIndex ? 'completed' : ''} ${idx === currentIndex ? 'active' : ''}">
                        <div class="timeline-icon"><i class="fas ${this.statusIcon(s.key)}"></i></div>
                        <div class="timeline-content">
                            <h4>${s.title}</h4>
                            <p>${s.desc}</p>
                            ${idx <= currentIndex && delivery.history && delivery.history[s.key] ? `<small class="text-muted">${new Date(delivery.history[s.key]).toLocaleString()}</small>` : ''}
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    }

    statusIcon(key) {
        return {
            pending: 'fa-clock',
            accepted: 'fa-user-check',
            picked_up: 'fa-box',
            in_transit: 'fa-truck',
            delivered: 'fa-check-circle'
        }[key] || 'fa-circle';
    }
}
