// Kitchen Dashboard Application
class KitchenDashboard {
    constructor() {
        this.currentView = 'orders';
        this.orders = [];
        this.menuItems = [];
        this.refreshInterval = null;
        this.init();
    }

    async init() {
        // Check if user has kitchen/admin role
        if (!window.auth.user || (window.auth.user.role !== 'kitchen' && window.auth.user.role !== 'admin')) {
            window.location.href = '/admin-login.html';
            return;
        }

        // Set user name
        const userNameEl = document.getElementById('userName');
        if (userNameEl) {
            userNameEl.textContent = window.auth.user.name;
        }

        this.setupEventListeners();
        await this.loadStats();
        await this.loadOrders();

        // Auto-refresh orders every 30 seconds
        this.refreshInterval = setInterval(() => {
            if (this.currentView === 'orders') {
                this.loadOrders();
            }
        }, 30000);
    }

    setupEventListeners() {
        // Sidebar Navigation
        const navItems = document.querySelectorAll('.desktop-nav-item');
        navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const view = e.currentTarget.dataset.view;
                this.switchView(view);
            });
        });

        // Logout
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', () => {
                window.auth.logout();
                window.location.href = '/login.html';
            });
        }

        // Refresh button
        const refreshBtn = document.getElementById('refreshOrdersBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.loadOrders();
                this.loadStats();
                this.showToast('Orders refreshed', 'success');
            });
        }

        // Add food button
        const addFoodBtn = document.getElementById('addFoodBtn');
        if (addFoodBtn) {
            addFoodBtn.addEventListener('click', () => this.openFoodModal());
        }

        // Food modal buttons
        const saveFoodBtn = document.getElementById('saveFoodBtn');
        if (saveFoodBtn) {
            saveFoodBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.saveFood();
            });
        }

        const cancelFoodBtn = document.getElementById('cancelFoodBtn');
        if (cancelFoodBtn) {
            cancelFoodBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.closeFoodModal();
            });
        }

        const closeFoodModalBtn = document.getElementById('closeFoodModalBtn');
        if (closeFoodModalBtn) {
            closeFoodModalBtn.addEventListener('click', () => this.closeFoodModal());
        }
    }

    switchView(view) {
        this.currentView = view;

        // Update nav items
        document.querySelectorAll('.desktop-nav-item').forEach(item => {
            if (item.dataset.view === view) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });

        // Hide all views
        document.querySelectorAll('.view-content').forEach(v => {
            v.classList.add('hidden');
        });

        // Show selected view
        const viewElement = document.getElementById(`${view}View`);
        if (viewElement) {
            viewElement.classList.remove('hidden');
        }

        // Update page title
        const titles = {
            orders: 'Orders Queue',
            menu: 'Menu Management',
            analytics: 'Analytics & Reports'
        };
        document.getElementById('pageTitle').textContent = titles[view] || 'Dashboard';

        // Load data for the view
        if (view === 'orders') {
            this.loadOrders();
        } else if (view === 'menu') {
            this.loadMenu();
        } else if (view === 'analytics') {
            this.loadAnalytics();
        }
    }

    async loadStats() {
        try {
            const response = await fetch('/api/orders/analytics/summary', {
                headers: window.auth.getAuthHeaders()
            });

            const data = await response.json();

            if (data.success) {
                const stats = data.analytics;

                document.getElementById('totalOrders').textContent = stats.total_orders;
                document.getElementById('pendingOrders').textContent =
                    (stats.status_counts.ordered || 0) + (stats.status_counts.preparing || 0);
                document.getElementById('completedOrders').textContent = stats.status_counts.completed || 0;
                document.getElementById('totalRevenue').textContent = `₹${stats.total_revenue}`;
            }
        } catch (error) {
            console.error('Error loading stats:', error);
        }
    }

    async loadOrders() {
        const container = document.getElementById('ordersQueue');
        if (!container) return;

        try {
            // Fetch all orders - backend will filter logic
            const response = await fetch('/api/orders', {
                headers: window.auth.getAuthHeaders()
            });

            const data = await response.json();

            if (data.success) {
                // Filter for active orders (ordered, preparing, ready)
                this.orders = data.orders.filter(o =>
                    o.status === 'ordered' || o.status === 'preparing' || o.status === 'ready'
                );
                this.renderOrders();
                await this.loadStats(); // Refresh stats
            }
        } catch (error) {
            console.error('Error loading orders:', error);
            this.showToast('Failed to load orders', 'error');
        }
    }

    renderOrders() {
        const container = document.getElementById('ordersQueue');
        if (!container) return;

        if (this.orders.length === 0) {
            container.innerHTML = `
        <div class="desktop-empty-state" style="text-align: center; padding: 48px; background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
          <div style="font-size: 4rem; margin-bottom: 1rem; color: var(--success);">
            <i class="fas fa-check-circle"></i>
          </div>
          <h3>All caught up!</h3>
          <p style="color: var(--gray-500);">No pending orders at the moment</p>
        </div>
      `;
            return;
        }

        container.innerHTML = this.orders.map(order => this.createOrderCard(order)).join('');
    }

    createOrderCard(order) {
        const statusClass = order.status;
        const timeAgo = this.getTimeAgo(new Date(order.created_at));
        const itemCount = order.order_items.reduce((sum, item) => sum + item.quantity, 0);

        return `
      <div class="desktop-order-card ${statusClass}">
        <div class="desktop-order-header">
          <div>
            <div class="desktop-order-number">
              ${order.order_number}
              <span class="desktop-order-status-badge ${statusClass}">${order.status.toUpperCase()}</span>
            </div>
            <div class="desktop-order-meta">
              <i class="fas fa-clock"></i> ${timeAgo} • 
              <i class="fas fa-user"></i> ${order.users?.name || 'Student'}
            </div>
          </div>
          <div style="text-align: right;">
            <div style="font-size: 1.5rem; font-weight: 700; color: var(--primary-orange);">
              ₹${parseFloat(order.total).toFixed(2)}
            </div>
            <div style="color: var(--gray-500); font-size: 0.875rem;">
              <i class="fas fa-stopwatch"></i> ${order.estimated_time || 15} min prep
            </div>
          </div>
        </div>

        <div class="desktop-order-items">
          ${order.order_items.map(item => `
            <div class="desktop-order-item">
              <span><strong>${item.quantity}x</strong> ${item.food_items?.name || 'Item'}</span>
              <span>₹${(parseFloat(item.price) * item.quantity).toFixed(2)}</span>
            </div>
          `).join('')}
          <div style="margin-top: 8px; font-size: 0.875rem; color: var(--gray-600); text-align: right;">
            Total Items: <strong>${itemCount}</strong>
          </div>
        </div>

        <div class="desktop-order-actions">
          ${order.status === 'ordered' ? `
            <button class="btn btn-warning btn-block" onclick="kitchen.updateOrderStatus('${order.id}', 'preparing')">
              <i class="fas fa-fire"></i> Start Preparing
            </button>
          ` : ''}
          
          ${order.status === 'preparing' ? `
            <button class="btn btn-success btn-block" onclick="kitchen.updateOrderStatus('${order.id}', 'ready')">
              <i class="fas fa-check"></i> Mark as Ready
            </button>
          ` : ''}
          
          ${order.status === 'ready' ? `
            <button class="btn btn-primary btn-block" onclick="kitchen.updateOrderStatus('${order.id}', 'completed')">
              <i class="fas fa-check-double"></i> Mark as Completed
            </button>
          ` : ''}
          
          <button class="btn btn-danger" onclick="kitchen.updateOrderStatus('${order.id}', 'cancelled')">
            <i class="fas fa-times"></i> Cancel
          </button>
        </div>
      </div>
    `;
    }

    async updateOrderStatus(orderId, status) {
        this.showLoading(true);

        try {
            const response = await fetch(`/api/orders/${orderId}/status`, {
                method: 'PATCH',
                headers: window.auth.getAuthHeaders(),
                body: JSON.stringify({ status })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || 'Failed to update order');
            }

            this.showToast(`Order marked as ${status}`, 'success');
            await this.loadOrders();
        } catch (error) {
            console.error('Error updating order:', error);
            this.showToast(error.message || 'Failed to update order', 'error');
        } finally {
            this.showLoading(false);
        }
    }

    async loadMenu() {
        const container = document.getElementById('menuList');
        if (!container) return;

        container.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';

        try {
            const response = await fetch('/api/menu');
            const data = await response.json();

            if (data.success) {
                this.menuItems = data.items;
                this.renderMenu();
            }
        } catch (error) {
            console.error('Error loading menu:', error);
            this.showToast('Failed to load menu', 'error');
        }
    }

    renderMenu() {
        const container = document.getElementById('menuList');
        if (!container) return;

        if (this.menuItems.length === 0) {
            container.innerHTML = `
        <div class="text-center" style="padding: 3rem; background: white; border-radius: 12px; grid-column: 1 / -1;">
          <i class="fas fa-utensils fa-3x" style="color: var(--gray-300); margin-bottom: 1rem;"></i>
          <h3>No menu items yet</h3>
          <p style="color: var(--gray-500);">Add items to start selling</p>
        </div>
      `;
            return;
        }

        container.innerHTML = this.menuItems.map(item => `
      <div class="desktop-order-card">
        <div style="display: flex; gap: 16px; margin-bottom: 16px;">
          <img src="${item.image_url || '/images/placeholder.png'}" 
               alt="${item.name}" 
               style="width: 80px; height: 80px; border-radius: 8px; object-fit: cover;"
               onerror="this.src='/images/placeholder.png'">
          
          <div style="flex: 1;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
              <h4 style="margin: 0; font-size: 1.125rem;">${item.name}</h4>
              <span style="font-weight: 700; color: var(--primary-orange);">₹${item.price}</span>
            </div>
            <p style="margin: 0 0 8px 0; color: var(--gray-600); font-size: 0.875rem;">
              ${item.category.charAt(0).toUpperCase() + item.category.slice(1)} • ${item.prep_time} min
            </p>
            <span class="desktop-order-status-badge ${item.availability === 'available' ? 'ready' : 'ordered'}" 
                  style="font-size: 0.75rem;">
              ${item.availability.replace('_', ' ').toUpperCase()}
            </span>
          </div>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
          <button class="btn btn-sm ${item.availability === 'available' ? 'btn-danger' : 'btn-success'}" 
                  onclick="kitchen.updateAvailability('${item.id}', '${item.availability === 'available' ? 'not_available' : 'available'}')">
            <i class="fas ${item.availability === 'available' ? 'fa-ban' : 'fa-check'}"></i> 
            ${item.availability === 'available' ? 'Make Unavailable' : 'Make Available'}
          </button>
          <div style="display: flex; gap: 8px;">
            <button class="btn btn-sm btn-secondary" style="flex: 1;" onclick="kitchen.editFood('${item.id}')">
              <i class="fas fa-edit"></i> Edit
            </button>
            <button class="btn btn-sm btn-danger" onclick="kitchen.deleteFood('${item.id}')">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>
    `).join('');
    }

    async updateAvailability(foodId, availability) {
        try {
            const response = await fetch(`/api/menu/${foodId}`, {
                method: 'PUT',
                headers: window.auth.getAuthHeaders(),
                body: JSON.stringify({ availability })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || 'Failed to update availability');
            }

            this.showToast('Availability updated', 'success');
            await this.loadMenu();
        } catch (error) {
            console.error('Error updating availability:', error);
            this.showToast(error.message || 'Failed to update availability', 'error');
        }
    }

    openFoodModal(foodId = null) {
        const modal = document.getElementById('foodModal');
        const title = document.getElementById('foodModalTitle');

        if (foodId) {
            const food = this.menuItems.find(f => f.id === foodId);
            if (food) {
                title.textContent = 'Edit Food Item';
                document.getElementById('foodId').value = food.id;
                document.getElementById('foodName').value = food.name;
                document.getElementById('foodCategory').value = food.category;
                document.getElementById('foodPrice').value = food.price;
                document.getElementById('foodPrepTime').value = food.prep_time;
                document.getElementById('foodDescription').value = food.description || '';
                document.getElementById('foodAvailability').value = food.availability;
            }
        } else {
            title.textContent = 'Add Food Item';
            document.getElementById('foodForm').reset();
            document.getElementById('foodId').value = '';
        }

        modal.classList.add('active');
    }

    closeFoodModal() {
        const modal = document.getElementById('foodModal');
        modal.classList.remove('active');
        document.getElementById('foodForm').reset();
    }

    async saveFood() {
        const form = document.getElementById('foodForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        const foodId = document.getElementById('foodId').value;
        const name = document.getElementById('foodName').value;
        const category = document.getElementById('foodCategory').value;
        const price = parseFloat(document.getElementById('foodPrice').value);
        const prepTime = parseInt(document.getElementById('foodPrepTime').value);
        const description = document.getElementById('foodDescription').value;
        const availability = document.getElementById('foodAvailability').value;
        const imageFile = document.getElementById('foodImage').files[0];

        this.showLoading(true);

        try {
            // Create or update food item
            const foodData = {
                name,
                category,
                price,
                prep_time: prepTime,
                description,
                availability
            };

            const url = foodId ? `/api/menu/${foodId}` : '/api/menu';
            const method = foodId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method,
                headers: window.auth.getAuthHeaders(),
                body: JSON.stringify(foodData)
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || 'Failed to save food item');
            }

            // Upload image if provided
            if (imageFile && data.item) {
                await this.uploadFoodImage(data.item.id, imageFile);
            }

            this.showToast(foodId ? 'Food item updated' : 'Food item added', 'success');
            this.closeFoodModal();
            await this.loadMenu();
        } catch (error) {
            console.error('Error saving food:', error);
            this.showToast(error.message || 'Failed to save food item', 'error');
        } finally {
            this.showLoading(false);
        }
    }

    async uploadFoodImage(foodId, file) {
        const formData = new FormData();
        formData.append('image', file);

        const response = await fetch(`/api/menu/${foodId}/image`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${window.auth.token}`
            },
            body: formData
        });

        if (!response.ok) {
            throw new Error('Failed to upload image');
        }
    }

    editFood(foodId) {
        this.openFoodModal(foodId);
    }

    async deleteFood(foodId) {
        if (!confirm('Are you sure you want to delete this food item?')) {
            return;
        }

        this.showLoading(true);

        try {
            const response = await fetch(`/api/menu/${foodId}`, {
                method: 'DELETE',
                headers: window.auth.getAuthHeaders()
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || 'Failed to delete food item');
            }

            this.showToast('Food item deleted', 'success');
            await this.loadMenu();
        } catch (error) {
            console.error('Error deleting food:', error);
            this.showToast(error.message || 'Failed to delete food item', 'error');
        } finally {
            this.showLoading(false);
        }
    }

    async loadAnalytics() {
        const container = document.getElementById('analyticsContent');
        if (!container) return;

        container.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';

        try {
            const response = await fetch('/api/orders/analytics/summary', {
                headers: window.auth.getAuthHeaders()
            });

            const data = await response.json();

            if (data.success) {
                this.renderAnalytics(data.analytics);
            }
        } catch (error) {
            console.error('Error loading analytics:', error);
            container.innerHTML = `
        <div class="text-center" style="padding: 2rem;">
          <p style="color: var(--error);">Failed to load analytics</p>
        </div>
      `;
        }
    }

    renderAnalytics(analytics) {
        const container = document.getElementById('analyticsContent');
        if (!container) return;

        container.innerHTML = `
      <div style="background: var(--white); border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
        <h3 style="margin-top: 0;">Today's Summary (${analytics.date})</h3>
        
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 20px;">
          <div style="padding: 20px; background: var(--gray-50); border-radius: 8px;">
            <p style="color: var(--gray-600); margin: 0 0 0.5rem 0;">Total Orders</p>
            <p style="font-size: 2rem; font-weight: 700; margin: 0;">${analytics.total_orders}</p>
          </div>
          
          <div style="padding: 20px; background: var(--gray-50); border-radius: 8px;">
            <p style="color: var(--gray-600); margin: 0 0 0.5rem 0;">Total Revenue</p>
            <p style="font-size: 2rem; font-weight: 700; margin: 0; color: var(--primary-orange);">₹${analytics.total_revenue}</p>
          </div>
          
          <div style="padding: 20px; background: var(--gray-50); border-radius: 8px;">
            <p style="color: var(--gray-600); margin: 0 0 0.5rem 0;">Avg Prep Time</p>
            <p style="font-size: 2rem; font-weight: 700; margin: 0;">${analytics.average_prep_time} min</p>
          </div>
        </div>

        <h4 style="margin-top: 32px; margin-bottom: 16px;">Order Status Breakdown</h4>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px;">
          <div style="padding: 16px; background: var(--info); color: var(--white); border-radius: 8px; text-align: center;">
            <p style="margin: 0; font-size: 1.5rem; font-weight: 700;">${analytics.status_counts.ordered || 0}</p>
            <p style="margin: 0; font-size: 0.875rem;">Ordered</p>
          </div>
          <div style="padding: 16px; background: var(--warning); color: var(--white); border-radius: 8px; text-align: center;">
            <p style="margin: 0; font-size: 1.5rem; font-weight: 700;">${analytics.status_counts.preparing || 0}</p>
            <p style="margin: 0; font-size: 0.875rem;">Preparing</p>
          </div>
          <div style="padding: 16px; background: var(--success); color: var(--white); border-radius: 8px; text-align: center;">
            <p style="margin: 0; font-size: 1.5rem; font-weight: 700;">${analytics.status_counts.ready || 0}</p>
            <p style="margin: 0; font-size: 0.875rem;">Ready</p>
          </div>
          <div style="padding: 16px; background: var(--gray-500); color: var(--white); border-radius: 8px; text-align: center;">
            <p style="margin: 0; font-size: 1.5rem; font-weight: 700;">${analytics.status_counts.completed || 0}</p>
            <p style="margin: 0; font-size: 0.875rem;">Completed</p>
          </div>
          <div style="padding: 16px; background: var(--error); color: var(--white); border-radius: 8px; text-align: center;">
            <p style="margin: 0; font-size: 1.5rem; font-weight: 700;">${analytics.status_counts.cancelled || 0}</p>
            <p style="margin: 0; font-size: 0.875rem;">Cancelled</p>
          </div>
        </div>
      </div>
    `;
    }

    getTimeAgo(date) {
        const seconds = Math.floor((new Date() - date) / 1000);

        if (seconds < 60) return `${seconds}s ago`;
        if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
        if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
        return `${Math.floor(seconds / 86400)}d ago`;
    }

    showLoading(show) {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            if (show) {
                overlay.classList.remove('hidden');
            } else {
                overlay.classList.add('hidden');
            }
        }
    }

    showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i> ${message}`;

        const container = document.getElementById('toastContainer');
        if (container) {
            container.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
    }
}

// Initialize kitchen dashboard when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.kitchen = new KitchenDashboard();
});
