class ShopManager {
    constructor(app) {
        this.app = app;
        this.shopService = new ShopService(this.app.notifier);
        this.shopUI = new ShopUI(document.getElementById('main-content'));
        this.currentShop = null;
        this.setupShopListeners();
    }

    setupShopListeners() {
        document.addEventListener('click', (e) => {
            if (e.target.closest('.shop-card') || e.target.closest('.view-shop-btn')) {
                const shopId = e.target.closest('[data-shop-id]')?.dataset.shopId;
                if (shopId) {
                    this.viewShop(parseInt(shopId));
                }
            }

            if (e.target.closest('.create-shop-action')) {
                this.showCreateShopModal();
            }

            // Listeners for the shop detail page
            if (e.target.closest('#manage-shop-btn')) {
                this.showShopManagement();
            }

            if (e.target.closest('#add-product-btn')) {
                this.showAddProductModal();
            }

            if (e.target.closest('.add-to-cart-btn')) {
                const productCard = e.target.closest('.product-card');
                // Pass product details directly to avoid an extra API call
                this.handleAddToCart(productCard);
            }
        });
    }

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

        // Allow both shop_owner and users who haven't set a role yet
        if (user.role && user.role !== 'shop_owner') {
            this.app.notifier.show('Only shop owners can create shops. Please update your role in settings.', 'error');
            return;
        }

        const modalInstance = new Modal({ title: 'Create New Shop', content: this.shopUI.getCreateShopModalContent() });
        const modal = modalInstance.show();

        const form = document.getElementById('create-shop-form');

        modal.addEventListener('click', (e) => {
            if (e.target.dataset.action === 'cancel') {
                modalInstance.close();
            }
        });

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            await this.handleCreateShop(form, modalInstance);
        });
    }

    async handleCreateShop(form, modalInstance) {
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating...';
        submitBtn.disabled = true;

        try {
            const imageFile = form.elements['image'].files[0];
            let imageUrl = null;

            if (imageFile) {
                const uploadFormData = new FormData();
                uploadFormData.append('image', imageFile);
                uploadFormData.append('type', 'shops');
                const uploadResponse = await fetch('api/upload.php', { method: 'POST', body: uploadFormData });
                const uploadResult = await uploadResponse.json();
                if (!uploadResult.success) throw new Error(uploadResult.message);
                imageUrl = uploadResult.url;
            }

            const data = {
                name: form.elements['name'].value.trim(),
                description: form.elements['description'].value.trim(),
                location: form.elements['location'].value.trim(),
                image: imageUrl,
                // lat/lng can be added back if needed
            };

            const response = await fetch('api/shops/create.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                this.app.notifier.show('Shop created successfully!', 'success');
                modalInstance.close();
                this.viewShop(result.shop_id);
            } else {
                this.app.notifier.show('Error: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('Error creating shop:', error);
            this.app.notifier.show(error.message || 'Failed to create shop.', 'error');
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    async viewShop(shopId) {
        try {
            const response = await fetch(`api/shops/get.php?id=${shopId}`);
            const data = await response.json();

            if (data.success) {
                this.currentShop = data.shop;
                this.showShopDetailPage();
            } else {
                this.app.notifier.show('Shop not found', 'error');
            }
        } catch (error) {
            console.error('Error loading shop:', error);
            this.app.notifier.show('Failed to load shop details', 'error');
        }
    }

    showShopDetailPage() {
        if (!this.currentShop) return;

        const canManage = (this.app.currentUser && this.app.currentUser.id === this.currentShop.owner_id) ||
            (this.app.currentUser && this.app.currentUser.role === 'admin');


        const shopHTML = `
            <div class="shop-detail-page">
                <div class="shop-header">
                    <div class="shop-hero">
                        <img src="${this.currentShop.image || 'https://images.unsplash.com/photo-1563016767-50f6d53a1d0b?ixlib=rb-4.0.3&auto=format&fit=crop&w=1000&q=80'}" alt="${this.currentShop.name}">
                        <div class="shop-info">
                            <h1>${this.currentShop.name}</h1>
                            <p class="shop-location">
                                <i class="fas fa-map-marker-alt"></i>
                                ${this.currentShop.location}
                            </p>
                            <p class="shop-description">${this.currentShop.description}</p>
                            ${canManage ? `
                                <button class="btn-primary" id="manage-shop-btn">
                                    <i class="fas fa-cog"></i> Manage Shop
                                </button>
                            ` : ''}
                        </div>
                    </div>
                </div>

                <div class="shop-content">
                    <div class="products-section">
                        <div class="section-title">
                            <h2>Products</h2>
                            ${canManage ? `
                                <button class="btn-primary" id="add-product-btn">
                                    <i class="fas fa-plus"></i> Add Product
                                </button>
                            ` : ''}
                        </div>
                        <div class="products-grid" id="products-grid">
                            <div class="loading">Loading products...</div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        const mainContent = document.getElementById('main-content');
        if (mainContent) {
            mainContent.innerHTML = shopHTML;
            this.loadShopProducts();
        }
    }

    async loadShopProducts() {
        if (!this.currentShop) return;

        try {
            const response = await fetch(`api/shops/products.php?shop_id=${this.currentShop.id}`);
            const data = await response.json();

            const productsGrid = document.getElementById('products-grid');
            if (!productsGrid) return;

            if (data.success && data.products) {
                // Only show available products on the public page
                const availableProducts = data.products.filter(p => p.is_available);
                if (availableProducts.length > 0) {
                    productsGrid.innerHTML = availableProducts.map(product => `
                        <div class="product-card" data-product-id="${product.id}">
                            <div class="product-image">
                                <img src="${product.image || 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&auto=format&fit=crop&w=500&q=80'}" alt="${product.name}">
                            </div>
                            <div class="product-info">
                                <h3>${product.name}</h3>
                                <p class="product-description">${product.description || 'No description'}</p>
                                <div class="product-price">$${parseFloat(product.price).toFixed(2)}</div>
                                <div class="product-actions">
                                    <button class="btn-primary add-to-cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</button>
                                </div>
                            </div>
                        </div>
                    `).join('');
                } else {
                    productsGrid.innerHTML = '<p>No products available in this shop at the moment.</p>';
                }
            }
        } catch (error) {
            console.error('Error loading products:', error);
        }
    }

    showShopManagement() {
        if (!this.currentShop || !this.app.currentUser) return;

        const modalInstance = new Modal({ title: `Manage ${this.currentShop.name}`, content: this.shopUI.getShopManagementModalContent(this.currentShop), size: 'large-modal' });
        const modal = modalInstance.show();
        this.setupShopManagementListeners(modal, modalInstance);
        this.loadManagementProducts();
    }

    setupShopManagementListeners(modal, modalInstance) {
        if (!modal) return;

        // Tab switching
        modal.addEventListener('click', (e) => {
            if (e.target.closest('.tab-btn')) {
                const tabBtn = e.target.closest('.tab-btn');
                const tabName = tabBtn.dataset.tab;

                // Update active tab
                modal.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
                modal.querySelectorAll('.tab-pane').forEach(pane => pane.classList.remove('active'));

                tabBtn.classList.add('active');
                modal.querySelector(`#${tabName}-tab`).classList.add('active');

                // Load orders when tab is clicked for the first time
                if (tabName === 'orders' && !modal.querySelector('#orders-tab').dataset.loaded) {
                    this.loadShopOrders();
                }
            }

            // Apply analytics filter
            if (e.target.closest('#apply-analytics-filter')) {
                // Reload analytics with new date range
                this.loadShopAnalytics();
            }

            // Add product from modal
            if (e.target.closest('#modal-add-product')) {
                modalInstance.close();
                this.showAddProductModal();
            }

            // Edit product
            if (e.target.closest('.edit-product')) {
                const productId = e.target.closest('.edit-product').dataset.productId;
                modalInstance.close();
                this.showAddProductModal(productId);
            }

            // Delete product
            if (e.target.closest('.delete-product')) {
                const productId = e.target.closest('.delete-product').dataset.productId;
                this.handleDeleteProduct(productId);
            }

            // Toggle product availability
            if (e.target.classList.contains('availability-toggle-checkbox')) {
                const checkbox = e.target;
                const productId = checkbox.dataset.productId;
                const isAvailable = checkbox.checked;
                this.handleToggleProductAvailability(productId, isAvailable);
            }
        });

        // Settings form submission
        const settingsForm = modal.querySelector('#shop-settings-form');
        settingsForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleUpdateShopSettings(settingsForm, modalInstance);
        });

        // Order status change
        modal.addEventListener('change', (e) => {
            if (e.target.classList.contains('order-status-select')) {
                this.handleUpdateOrderStatus(e.target.dataset.orderId, e.target.value);
            }
        });
    }

    async showAddProductModal(productId = null) {
        const modalInstance = new Modal({
            title: productId ? 'Edit Product' : 'Add New Product',
            content: this.shopUI.getAddProductModalContent(productId)
        });
        const modal = modalInstance.show();

        const form = document.getElementById('add-product-form');

        if (productId) {
            try {
                const response = await fetch(`api/shops/get_product.php?id=${productId}`);
                const result = await response.json();
                if (result.success) {
                    this.shopUI.fillProductForm(form, result.product);
                } else {
                    this.app.notifier.show('Failed to load product data.', 'error');
                    modalInstance.close();
                }
            } catch (error) {
                console.error('Error fetching product for edit:', error);
                this.app.notifier.show('Error fetching product data.', 'error');
                modalInstance.close();
            }
        }

        modal.addEventListener('click', (e) => {
            if (e.target.dataset.action === 'cancel') {
                modalInstance.close();
            }
        });

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            await this.handleAddProduct(form, modalInstance);
        });
    }

    async handleAddProduct(form, modalInstance) {
        if (!this.currentShop) return;

        const imageFile = form.elements['image'].files[0];
        let imageUrl = null;

        try {
            if (imageFile) {
                const uploadFormData = new FormData();
                uploadFormData.append('image', imageFile);
                uploadFormData.append('type', 'products');
                const uploadResponse = await fetch('api/upload.php', { method: 'POST', body: uploadFormData });
                const uploadResult = await uploadResponse.json();
                if (!uploadResult.success) throw new Error(uploadResult.message);
                imageUrl = uploadResult.url;
            }

            const productId = form.elements['product_id'].value;
            const data = {
                name: form.elements['name'].value,
                description: form.elements['description'].value,
                price: parseFloat(form.elements['price'].value),
                category: form.elements['category'].value,
                image: imageUrl,
                shop_id: this.currentShop.id
            };

            let url = 'api/shops/add_product.php';
            let successMessage = 'Product added successfully!';

            if (productId) {
                url = 'api/shops/update_product.php';
                data.product_id = productId;
                successMessage = 'Product updated successfully!';
            }
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    ...data,
                    shop_id: this.currentShop.id
                })
            });

            const result = await response.json();

            if (result.success) {
                this.app.notifier.show(successMessage, 'success');
                modalInstance.close();
                this.loadManagementProducts(); // Refresh management list
                this.loadShopProducts(); // Refresh public products list
            } else {
                this.app.notifier.show('Error: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('Error adding product:', error);
            this.app.notifier.show(error.message || 'Failed to save product.', 'error');
        }
    }

    async loadManagementProducts() {
        if (!this.currentShop) return;

        try {
            const response = await fetch(`api/shops/products.php?shop_id=${this.currentShop.id}`);
            const data = await response.json();

            const productsContainer = document.getElementById('management-products');
            if (!productsContainer) return;

            if (data.success && data.products) {
                productsContainer.innerHTML = data.products.length > 0 ? data.products.map(product => `
                    <div class="management-product-item">
                        <div class="product-image">
                            <img src="${product.image || 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&auto=format&fit=crop&w=100&q=80'}" alt="${product.name}">
                        </div>
                        <div class="product-details">
                            <h4>${product.name}</h4>
                            <p>${product.description || 'No description'}</p>
                            <div class="product-meta">
                                <span class="price">$${parseFloat(product.price).toFixed(2)}</span>
                                <span class="category">${product.category}</span>
                            </div>
                        </div>
                        <div class="product-actions">
                            <label class="availability-toggle">
                                <input type="checkbox" class="availability-toggle-checkbox" data-product-id="${product.id}" ${product.is_available ? 'checked' : ''}>
                                <span class="availability-toggle-slider"></span>
                            </label>
                            <button class="btn-secondary edit-product" data-product-id="${product.id}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn-danger delete-product" data-product-id="${product.id}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `).join('') : '<p>No products found. Add one to get started!</p>';
            } else {
                productsContainer.innerHTML = '<p>No products found</p>';
            }
        } catch (error) {
            console.error('Error loading management products:', error);
            const productsContainer = document.getElementById('management-products');
            if (productsContainer) {
                productsContainer.innerHTML = '<p>Error loading products</p>';
            }
        }
    }

    async handleDeleteProduct(productId) {
        const confirmed = await this.app.showConfirm('Are you sure you want to delete this product? This action cannot be undone.', 'Delete Product');
        if (!confirmed) {
            return;
        }

        try {
            const response = await fetch('api/shops/delete_product.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ product_id: productId, shop_id: this.currentShop.id })
            });

            const result = await response.json();

            if (result.success) {
                this.app.notifier.show('Product deleted successfully.', 'success');
                // Remove the product item from the DOM
                const productItem = document.querySelector(`.management-product-item[data-product-id="${productId}"]`);
                if (productItem) {
                    productItem.remove();
                }
                // Also refresh the main shop page product list if it's currently displayed
                this.loadShopProducts();
            } else {
                this.app.notifier.show('Error deleting product: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('Error deleting product:', error);
            this.app.notifier.show('Failed to delete product.', 'error');
        }
    }

    async handleToggleProductAvailability(productId, isAvailable) {
        try {
            const response = await fetch('api/shops/toggle_product.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    product_id: productId,
                    shop_id: this.currentShop.id,
                    is_available: isAvailable
                })
            });

            const result = await response.json();

            if (!result.success) {
                this.app.notifier.show('Error updating product status: ' + result.message, 'error');
                // Revert the checkbox state on failure
                const checkbox = document.querySelector(`.availability-toggle-checkbox[data-product-id="${productId}"]`);
                if (checkbox) checkbox.checked = !isAvailable;
            }
        } catch (error) {
            console.error('Error toggling product availability:', error);
        }
    }

    async loadShopOrders() {
        if (!this.currentShop) return;

        const ordersContainer = document.getElementById('orders-tab');
        if (!ordersContainer) return;

        ordersContainer.innerHTML = '<div class="loading">Loading orders...</div>';

        try {
            const response = await fetch(`api/shops/orders.php?shop_id=${this.currentShop.id}`);
            const result = await response.json();

            if (result.success && result.orders) {
                ordersContainer.dataset.loaded = 'true'; // Mark as loaded
                if (result.orders.length > 0) {
                    ordersContainer.innerHTML = result.orders.map(order => this.renderShopOrderItem(order)).join('');
                } else {
                    ordersContainer.innerHTML = '<p>No orders found for this shop.</p>';
                }
            } else {
                ordersContainer.innerHTML = `<p>Error: ${result.message || 'Could not load orders.'}</p>`;
            }
        } catch (error) {
            console.error('Error loading shop orders:', error);
            ordersContainer.innerHTML = '<p>Failed to load orders.</p>';
        }
    }

    renderShopOrderItem(order) {
        const statuses = ['pending', 'confirmed', 'preparing', 'ready', 'picked_up', 'delivered', 'cancelled'];
        const statusOptions = statuses.map(s =>
            `<option value="${s}" ${order.status === s ? 'selected' : ''}>${s.charAt(0).toUpperCase() + s.slice(1)}</option>`
        ).join('');

        return `
            <div class="delivery-card">
                <div class="delivery-info">
                    <h4>Order #${order.id}</h4>
                    <p><strong>Customer:</strong> ${order.customer_name}</p>
                    <p><strong>Date:</strong> ${new Date(order.created_at).toLocaleDateString()}</p>
                    <p><strong>Total:</strong> $${parseFloat(order.total_amount).toFixed(2)}</p>
                </div>
                <div class="delivery-actions">
                    <select class="order-status-select status-select" data-order-id="${order.id}">
                        ${statusOptions}
                    </select>
                </div>
            </div>
        `;
    }

    async handleUpdateOrderStatus(orderId, status) {
        try {
            const response = await fetch('api/shops/update_order_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    order_id: orderId,
                    status: status,
                    shop_id: this.currentShop.id
                })
            });

            const result = await response.json();

            if (!result.success) {
                this.app.notifier.show(`Failed to update order status: ${result.message}`, 'error');
                // Optionally revert the select box on failure
                this.loadShopOrders();
            } else {
                this.app.notifier.show(`Order status updated to ${status}`, 'info');
                console.log(`Order ${orderId} status updated to ${status}`);
            }
        } catch (error) {
            console.error('Error updating order status:', error);
            this.app.notifier.show('An error occurred while updating the order status.', 'error');
        }
    }

    async handleUpdateShopSettings(form, modalInstance) {
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = 'Saving...';
        submitBtn.disabled = true;

        try {
            const imageFile = form.elements['image'].files[0];
            let imageUrl = null;

            if (imageFile) {
                const uploadFormData = new FormData();
                uploadFormData.append('image', imageFile);
                uploadFormData.append('type', 'shops');
                const uploadResponse = await fetch('api/upload.php', { method: 'POST', body: uploadFormData });
                const uploadResult = await uploadResponse.json();
                if (!uploadResult.success) throw new Error(uploadResult.message);
                imageUrl = uploadResult.url;
            }

            const data = {
                shop_id: this.currentShop.id,
                name: form.elements['name'].value,
                description: form.elements['description'].value,
                location: form.elements['location'].value,
                image: imageUrl
            };

            const response = await fetch('api/shops/update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                this.app.notifier.show('Shop settings updated successfully!', 'success');
                modalInstance.close();
                // Re-load the shop to see the changes
                this.viewShop(this.currentShop.id);
            } else {
                this.app.notifier.show('Error updating settings: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('Error updating shop settings:', error);
            this.app.notifier.show(error.message || 'Failed to update shop settings.', 'error');
        } finally {
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
        }
    }

    async handleAddToCart(productCardElement) {
        try {
            const productId = productCardElement.dataset.productId;
            const productName = productCardElement.querySelector('.product-info h3').textContent;
            const productPrice = parseFloat(productCardElement.querySelector('.product-price').textContent.replace('$', ''));
            const productImage = productCardElement.querySelector('.product-image img').src;

            const product = {
                id: productId,
                name: productName,
                price: productPrice,
                image: productImage,
                shop_id: this.currentShop.id // Assuming currentShop is always set when viewing products
            };
            this.app.cartManager.addToCart(product);
        } catch (error) {
            console.error('Error fetching product for cart:', error);
        }
    }
}