import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import api from '../utils/api';
import { useToast } from '../App';
import LoadingState from '../components/LoadingState';
import ProductSyncSettings from '../components/ProductSyncSettings';
import ConfirmDialog from '../components/ConfirmDialog';
import Categories from './Categories';
import Tags from './Tags';
import Brands from './Brands';
import Attributes from './Attributes';
import Reviews from './Reviews';


const Products = () => {
    const { showSuccess, showError } = useToast();
    const navigate = useNavigate();
    const location = useLocation();
    const [searchParams, setSearchParams] = useSearchParams();

    // Get initial tab from URL or default to 'products'
    const initialTab = searchParams.get('tab') || 'products';

    const [products, setProducts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(0);
    const [rowsPerPage, setRowsPerPage] = useState(25);
    const [totalCount, setTotalCount] = useState(0);
    const [selected, setSelected] = useState([]);
    const [viewDialogOpen, setViewDialogOpen] = useState(false);
    const [viewingProduct, setViewingProduct] = useState(null);
    const [syncing, setSyncing] = useState(false);
    const [activeTab, setActiveTab] = useState(initialTab);
    const [confirmDialog, setConfirmDialog] = useState({ isOpen: false, action: null, data: null });
    const [googleSheetsEnabled, setGoogleSheetsEnabled] = useState(false);
    const [googleSheetsConnected, setGoogleSheetsConnected] = useState(false);

    // Function to change tab and update URL
    const handleTabChange = (tab) => {
        setActiveTab(tab);
        setSearchParams({ tab });
    };
    const [stockUpdateDialog, setStockUpdateDialog] = useState({
        isOpen: false,
        quantity: '',
        manageStock: true,
        selectedProducts: []
    });

    // Filters
    const [filters, setFilters] = useState({
        search: '',
        status: '',
        category: '',
        stockStatus: ''
    });

    const productStatuses = [
        { value: '', label: 'All Statuses' },
        { value: 'publish', label: 'Published' },
        { value: 'draft', label: 'Draft' },
        { value: 'private', label: 'Private' }
    ];

    const stockStatuses = [
        { value: '', label: 'All Stock Status' },
        { value: 'instock', label: 'In Stock' },
        { value: 'outofstock', label: 'Out of Stock' },
        { value: 'onbackorder', label: 'On Backorder' }
    ];

    useEffect(() => {
        loadSettings();
    }, []);

    useEffect(() => {
        if (activeTab === 'products') {
            loadProducts();
        } else {
            // Reset loading state when switching away from products tab
            setLoading(false);
        }
    }, [page, rowsPerPage, filters, activeTab]);

    const loadSettings = async () => {
        try {
            const response = await api.getSettings();
            if (response.success && response.settings) {
                setGoogleSheetsEnabled(response.settings.google_sheets_mode_enabled || false);
                setGoogleSheetsConnected(response.settings.google_sheets_connected || false);
            }
        } catch (err) {
            console.error('Failed to load settings:', err);
        }
    };

    const loadProducts = async () => {
        try {
            setLoading(true);

            const params = {
                page: page + 1,
                per_page: rowsPerPage
            };

            if (filters.search && filters.search.trim()) {
                params.search = filters.search.trim();
            }

            if (filters.status) {
                params.status = filters.status;
            }

            if (filters.stockStatus) {
                params.stock_status = filters.stockStatus;
            }

            const response = await api.getProducts(params);

            if (response.success) {
                setProducts(response.products || []);
                setTotalCount(response.total || 0);
            } else {
                throw new Error(response.message || 'Failed to load products');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleFilterChange = (field, value) => {
        setFilters(prev => ({
            ...prev,
            [field]: value
        }));
        setPage(0);
    };

    const clearFilters = () => {
        setFilters({
            search: '',
            status: '',
            category: '',
            stockStatus: ''
        });
        setPage(0);
    };

    const handleSelectAll = (event) => {
        if (event.target.checked) {
            setSelected(products.map(product => product.id));
        } else {
            setSelected([]);
        }
    };

    const handleSelectOne = (productId) => {
        setSelected(prev => {
            if (prev.includes(productId)) {
                return prev.filter(id => id !== productId);
            } else {
                return [...prev, productId];
            }
        });
    };

    const handleEditProduct = (product) => {
        navigate(`/products/edit/${product.id}`);
    };

    const handleViewProduct = async (product) => {
        try {
            // Fetch full product details including descriptions and gallery
            const response = await api.get(`/products/${product.id}`);
            if (response.success && response.product) {
                setViewingProduct(response.product);
            } else {
                // Fallback to list data if API fails
                setViewingProduct(product);
            }
            setViewDialogOpen(true);
        } catch (error) {
            console.error('Error fetching product details:', error);
            // Fallback to list data
            setViewingProduct(product);
            setViewDialogOpen(true);
        }
    };

    const handleSync = async () => {
        try {
            setSyncing(true);

            // Get spreadsheet settings from backend
            const settingsResponse = await api.getSettings();
            const spreadsheetUrl = settingsResponse.settings?.spreadsheet_url;
            const sheetName = settingsResponse.settings?.sheet_configs?.products?.tabName || 'Products';

            if (!spreadsheetUrl) {
                showError('Please configure Google Sheets URL in Settings first');
                return;
            }

            const response = await api.syncAllProducts(spreadsheetUrl, sheetName);

            if (response.success) {
                await loadProducts();
                showSuccess(response.message || 'Products synced successfully');
            } else {
                throw new Error(response.message || 'Sync failed');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSyncing(false);
        }
    };

    const handleExport = async () => {
        try {
            const response = await api.exportProducts(filters, 'csv');

            if (response.success && response.download_url) {
                window.open(response.download_url, '_blank');
                showSuccess('Export started successfully');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const handleBulkStockUpdate = () => {
        if (selected.length === 0) {
            showError('Please select products to update');
            return;
        }

        // Get selected products details
        const selectedProductsData = products.filter(p => selected.includes(p.id));

        // Check if any product has stock managed
        const hasStockManaged = selectedProductsData.some(p => p.manage_stock);

        // Get average or first stock quantity as default
        const stockQuantities = selectedProductsData
            .filter(p => p.manage_stock && p.stock_quantity)
            .map(p => p.stock_quantity);
        const avgStock = stockQuantities.length > 0
            ? Math.round(stockQuantities.reduce((a, b) => a + b, 0) / stockQuantities.length)
            : '';

        setStockUpdateDialog({
            isOpen: true,
            quantity: avgStock,
            manageStock: true,
            selectedProducts: selectedProductsData
        });
    };

    const executeStockUpdate = async () => {
        if (!stockUpdateDialog.manageStock) {
            showError('Please enable "Manage Stock" to set stock quantity');
            return;
        }

        const quantity = parseInt(stockUpdateDialog.quantity);
        if (isNaN(quantity) || quantity < 0) {
            showError('Please enter a valid stock quantity');
            return;
        }

        try {
            // Prepare stock updates in the format backend expects
            const stockUpdates = selected.map(productId => ({
                product_id: productId,
                quantity: quantity
            }));

            const response = await api.bulkUpdateProductStock(stockUpdates);

            if (response.success) {
                await loadProducts();
                setSelected([]);
                showSuccess(`Stock updated for ${selected.length} products`);
                setStockUpdateDialog({
                    isOpen: false,
                    quantity: '',
                    manageStock: true,
                    selectedProducts: []
                });
            } else {
                throw new Error(response.message || 'Failed to update stock');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const handleBulkStatusUpdate = async (status) => {
        if (selected.length === 0) {
            showError('Please select products to update');
            return;
        }

        const statusLabel = status === 'publish' ? 'published' : 'draft';
        setConfirmDialog({
            isOpen: true,
            action: 'bulkStatus',
            data: { status, statusLabel }
        });
    };

    const handleBulkDelete = async (force = false) => {
        if (selected.length === 0) {
            showError('Please select products to delete');
            return;
        }

        const action = force ? 'permanently delete' : 'move to trash';
        setConfirmDialog({
            isOpen: true,
            action: 'bulkDelete',
            data: { force, action }
        });
    };

    const executeConfirmedAction = async () => {
        const { action, data } = confirmDialog;

        try {
            if (action === 'bulkStatus') {
                const response = await api.bulkUpdateProductStatus(selected, data.status);
                if (response.success) {
                    await loadProducts();
                    setSelected([]);
                    showSuccess(`${selected.length} products set to ${data.statusLabel}`);
                } else {
                    throw new Error(response.message || 'Failed to update status');
                }
            } else if (action === 'bulkDelete') {
                const response = await api.bulkDeleteProducts(selected, data.force);
                if (response.success) {
                    await loadProducts();
                    setSelected([]);
                    showSuccess(`${selected.length} products ${data.force ? 'deleted permanently' : 'moved to trash'}`);
                } else {
                    throw new Error(response.message || `Failed to ${data.action} products`);
                }
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const getStockStatusChipClass = (stockStatus) => {
        const statusClasses = {
            instock: 'chip-success',
            outofstock: 'chip-danger',
            onbackorder: 'chip-warning'
        };
        return statusClasses[stockStatus] || 'chip-secondary';
    };

    const formatCurrency = (amount, currency = 'USD') => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency
        }).format(amount);
    };

    const handlePageChange = (newPage) => {
        setPage(newPage);
    };

    const handleRowsPerPageChange = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };

    // Only show full-page loader on initial load of products tab
    const isInitialLoad = activeTab === 'products' && loading && products.length === 0 && !filters.search && !filters.status;

    if (isInitialLoad) {
        return (
            <div className="page">
                <div className="container container-xl">
                    <LoadingState message="Loading products..." />
                </div>
            </div>
        );
    }

    return (
        <div className="page products">
            <div className="container product-container container-xl">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <h1>Products Management</h1>
                        <p>Manage WooCommerce products with inventory and stock synchronization</p>
                    </div>
                </div>



                {/* Main Layout with Sidebar */}
                <div className="products-layout">
                    {/* Sidebar */}
                    <div className="products-sidebar">
                        <div className="sidebar-tabs">
                            <button
                                className={`sidebar-tab ${activeTab === 'products' ? 'active' : ''}`}
                                onClick={() => handleTabChange('products')}
                            >
                                <span className="tab-icon">📦</span>
                                <span className="tab-label">Products List</span>
                            </button>
                            <button
                                className={`sidebar-tab ${activeTab === 'categories' ? 'active' : ''}`}
                                onClick={() => handleTabChange('categories')}
                            >
                                <span className="tab-icon">🏷️</span>
                                <span className="tab-label">Categories</span>
                            </button>
                            <button
                                className={`sidebar-tab ${activeTab === 'tags' ? 'active' : ''}`}
                                onClick={() => handleTabChange('tags')}
                            >
                                <span className="tab-icon">🔖</span>
                                <span className="tab-label">Tags</span>
                            </button>
                            <button
                                className={`sidebar-tab ${activeTab === 'brands' ? 'active' : ''}`}
                                onClick={() => handleTabChange('brands')}
                            >
                                <span className="tab-icon">🎨</span>
                                <span className="tab-label">Brands</span>
                            </button>
                            <button
                                className={`sidebar-tab ${activeTab === 'attributes' ? 'active' : ''}`}
                                onClick={() => handleTabChange('attributes')}
                            >
                                <span className="tab-icon">⚙️</span>
                                <span className="tab-label">Attributes</span>
                            </button>
                            <button
                                className={`sidebar-tab ${activeTab === 'reviews' ? 'active' : ''}`}
                                onClick={() => handleTabChange('reviews')}
                            >
                                <span className="tab-icon">⭐</span>
                                <span className="tab-label">Reviews</span>
                            </button>
                            {googleSheetsEnabled && (
                                <button
                                    className={`sidebar-tab ${activeTab === 'sync-settings' ? 'active' : ''}`}
                                    onClick={() => handleTabChange('sync-settings')}
                                >
                                    <span className="tab-icon">📊</span>
                                    <span className="tab-label">GS Export Settings</span>
                                </button>
                            )}
                        </div>
                    </div>

                    {/* Main Content */}
                    <div className="products-main-content">
                        {activeTab === 'products' && (
                            <div className="products-container">
                                <div className="page-header">
                                    <div className="page-actions">
                                        <button
                                            className="btn btn-success btn-sm"
                                            onClick={() => navigate('/products/add')}
                                        >
                                            +  Create Product
                                        </button>
                                        <button
                                            className="btn btn-secondary btn-sm"
                                            onClick={handleExport}
                                        >
                                            📥 Export CSV
                                        </button>
                                        <button
                                            className={`btn btn-primary btn-sm ${syncing ? 'btn-loading' : ''}`}
                                            onClick={handleSync}
                                            disabled={syncing}
                                        >
                                            {syncing ? (
                                                <>
                                                    <div className="spinner"></div>
                                                    Exporting...
                                                </>
                                            ) : (
                                                '🔄 Export to GS'
                                            )}
                                        </button>
                                        <button
                                            className="btn btn-secondary btn-sm"
                                            onClick={loadProducts}
                                            disabled={loading}
                                        >
                                            🔄 Refresh
                                        </button>
                                    </div>
                                </div>

                                {/* Filters Bar */}
                                <div className="filters-bar">
                                    <div className="filters-row">
                                        <div className="filter-item filter-search">
                                            <input
                                                type="text"
                                                placeholder="🔍 Search products..."
                                                value={filters.search}
                                                onChange={(e) => handleFilterChange('search', e.target.value)}
                                                className="search-input"
                                            />
                                        </div>
                                        <div className="filter-item">
                                            <select
                                                value={filters.status}
                                                onChange={(e) => handleFilterChange('status', e.target.value)}
                                                className="filter-select"
                                            >
                                                {productStatuses.map(status => (
                                                    <option key={status.value} value={status.value}>
                                                        {status.label}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>
                                        <div className="filter-item">
                                            <select
                                                value={filters.stockStatus}
                                                onChange={(e) => handleFilterChange('stockStatus', e.target.value)}
                                                className="filter-select"
                                            >
                                                {stockStatuses.map(status => (
                                                    <option key={status.value} value={status.value}>
                                                        {status.label}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>
                                        <div className="filter-item">
                                            <button
                                                className="btn btn-secondary btn-clear"
                                                onClick={clearFilters}
                                                title="Clear all filters"
                                            >
                                                ✕ Clear
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                {/* Bulk Actions */}
                                {selected.length > 0 && (
                                    <div className="card mb-4">
                                        <div className="card-content">
                                            <div className="bulk-actions flex items-center justify-between">
                                                <div className="bulk-info">
                                                    <strong>{selected.length} products selected</strong>
                                                </div>
                                                <div className="bulk-buttons flex gap-2">
                                                    <button
                                                        className="btn btn-primary btn-sm"
                                                        onClick={() => navigate('/products/bulk-edit', { state: { selectedProducts: selected } })}
                                                    >
                                                        ✏️ Bulk Edit
                                                    </button>
                                                    <button
                                                        className="btn btn-primary btn-sm"
                                                        onClick={() => handleBulkStockUpdate()}
                                                    >
                                                        Update Stock
                                                    </button>
                                                    <button
                                                        className="btn btn-success btn-sm"
                                                        onClick={() => handleBulkStatusUpdate('publish')}
                                                    >
                                                        Publish
                                                    </button>
                                                    <button
                                                        className="btn btn-warning btn-sm"
                                                        onClick={() => handleBulkStatusUpdate('draft')}
                                                    >
                                                        Set to Draft
                                                    </button>
                                                    <button
                                                        className="btn btn-warning btn-sm"
                                                        onClick={() => handleBulkDelete(false)}
                                                    >
                                                        Move to Trash
                                                    </button>
                                                    <button
                                                        className="btn btn-danger btn-sm"
                                                        onClick={() => handleBulkDelete(true)}
                                                    >
                                                        Delete Permanently
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* Products Table */}
                                <div className="card">
                                    <div className="table-container">
                                        <table className="products-table">
                                            <thead>
                                                <tr>
                                                    <th className="checkbox-col">
                                                        <input
                                                            type="checkbox"
                                                            checked={products.length > 0 && selected.length === products.length}
                                                            onChange={handleSelectAll}
                                                        />
                                                    </th>
                                                    <th>Product</th>
                                                    <th>SKU</th>
                                                    <th>Stock</th>
                                                    <th>Price</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {loading ? (
                                                    <tr>
                                                        <td colSpan="7" className="text-center">
                                                            <LoadingState message="Loading products..." />
                                                        </td>
                                                    </tr>
                                                ) : products.length === 0 ? (
                                                    <tr>
                                                        <td colSpan="7" className="text-center">
                                                            <div className="empty-state">
                                                                <div className="empty-icon">📦</div>
                                                                <p>No products found</p>
                                                                <p className="text-gray-600">Try adjusting your filters or sync data</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                ) : (
                                                    products.map((product) => (
                                                        <tr key={product.id} className="product-row">
                                                            <td className="checkbox-col">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={selected.includes(product.id)}
                                                                    onChange={() => handleSelectOne(product.id)}
                                                                />
                                                            </td>
                                                            <td>
                                                                <div className="product-info">
                                                                    <div className="product-image">
                                                                        {product.image ? (
                                                                            <img src={product.image} alt={product.name} />
                                                                        ) : (
                                                                            <div className="no-image">📦</div>
                                                                        )}
                                                                    </div>
                                                                    <div className="product-details">
                                                                        <div className="product-name">
                                                                            {product.name}
                                                                        </div>
                                                                        <div className="product-type text-gray-600">
                                                                            {product.type || 'Simple'}
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div className="product-sku">
                                                                    {product.sku || 'N/A'}
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div className="stock-info">
                                                                    <div className={`chip ${getStockStatusChipClass(product.stock_status)}`}>
                                                                        {product.stock_status}
                                                                    </div>
                                                                    {product.manage_stock && (
                                                                        <div className="stock-quantity text-gray-600">
                                                                            Qty: {product.stock_quantity || 0}
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div className="product-price font-semibold">
                                                                    {product.price ? formatCurrency(product.price) : 'N/A'}
                                                                </div>
                                                                {product.sale_price && (
                                                                    <div className="sale-price text-gray-600">
                                                                        Sale: {formatCurrency(product.sale_price)}
                                                                    </div>
                                                                )}
                                                            </td>
                                                            <td>
                                                                <div className={`chip ${product.status === 'publish' ? 'chip-success' : 'chip-warning'}`}>
                                                                    {product.status}
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div className="product-actions flex gap-1">
                                                                    <button
                                                                        className="btn btn-secondary btn-sm"
                                                                        onClick={() => handleEditProduct(product)}
                                                                        title="Edit Product"
                                                                    >
                                                                        ✏️
                                                                    </button>
                                                                    <button
                                                                        className="btn btn-secondary btn-sm"
                                                                        onClick={() => handleViewProduct(product)}
                                                                        title="View Product"
                                                                    >
                                                                        👁️
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    ))
                                                )}
                                            </tbody>
                                        </table>
                                    </div>

                                    {/* Pagination */}
                                    {totalCount > 0 && (
                                        <div className="table-pagination">
                                            <div className="pagination-info">
                                                Showing {page * rowsPerPage + 1} to {Math.min((page + 1) * rowsPerPage, totalCount)} of {totalCount} products
                                            </div>
                                            <div className="pagination-controls flex items-center gap-2">
                                                <select
                                                    value={rowsPerPage}
                                                    onChange={handleRowsPerPageChange}
                                                    className="rows-per-page"
                                                >
                                                    <option value={10}>10 per page</option>
                                                    <option value={25}>25 per page</option>
                                                    <option value={50}>50 per page</option>
                                                    <option value={100}>100 per page</option>
                                                </select>
                                                <button
                                                    className="btn btn-secondary btn-sm"
                                                    onClick={() => handlePageChange(page - 1)}
                                                    disabled={page === 0}
                                                >
                                                    ← Previous
                                                </button>
                                                <span className="page-info">
                                                    Page {page + 1} of {Math.ceil(totalCount / rowsPerPage)}
                                                </span>
                                                <button
                                                    className="btn btn-secondary btn-sm"
                                                    onClick={() => handlePageChange(page + 1)}
                                                    disabled={(page + 1) * rowsPerPage >= totalCount}
                                                >
                                                    Next →
                                                </button>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}

                        {activeTab === 'categories' && (
                            <Categories />
                        )}

                        {activeTab === 'tags' && (
                            <Tags />
                        )}

                        {activeTab === 'brands' && (
                            <Brands />
                        )}

                        {activeTab === 'attributes' && (
                            <Attributes />
                        )}

                        {activeTab === 'reviews' && (
                            <Reviews />
                        )}

                        {activeTab === 'sync-settings' && (
                            <>
                                {!googleSheetsConnected && (
                                    <div className="alert alert-warning" style={{ marginBottom: '20px' }}>
                                        <div className="alert-content">
                                            <strong>⚠️ Google Sheets Not Connected</strong>
                                            <p style={{ margin: '8px 0 0 0' }}>
                                                Please configure Google Sheets from <a href="#/settings?tab=google-sheets" style={{ color: 'inherit', textDecoration: 'underline' }}>Settings → 📊 Google Sheets</a> to use the export feature.
                                            </p>
                                        </div>
                                    </div>
                                )}
                                <ProductSyncSettings products={products} />
                            </>
                        )}
                    </div>
                </div>

                {/* View Product Modal */}
                {viewDialogOpen && (
                    <ProductViewModal
                        product={viewingProduct}
                        onClose={() => {
                            setViewDialogOpen(false);
                            setViewingProduct(null);
                        }}
                    />
                )}

                {/* Confirmation Dialog */}
                <ConfirmDialog
                    isOpen={confirmDialog.isOpen}
                    onClose={() => setConfirmDialog({ isOpen: false, action: null, data: null })}
                    onConfirm={executeConfirmedAction}
                    title={confirmDialog.action === 'bulkStatus' ? 'Confirm Status Update' : 'Confirm Delete'}
                    confirmText={confirmDialog.action === 'bulkStatus' ? 'Update Status' : 'Delete'}
                    confirmButtonClass={confirmDialog.action === 'bulkDelete' ? 'btn-danger' : 'btn-primary'}
                >
                    {confirmDialog.action === 'bulkStatus' && (
                        <p>Are you sure you want to set <strong>{selected.length} products</strong> to <strong>{confirmDialog.data?.statusLabel}</strong>?</p>
                    )}
                    {confirmDialog.action === 'bulkDelete' && (
                        <>
                            <p>Are you sure you want to <strong>{confirmDialog.data?.action}</strong> <strong>{selected.length} products</strong>?</p>
                            {confirmDialog.data?.force && <p className="text-danger">This action cannot be undone.</p>}
                        </>
                    )}
                </ConfirmDialog>

                {/* Stock Update Dialog */}
                <ConfirmDialog
                    isOpen={stockUpdateDialog.isOpen}
                    onClose={() => setStockUpdateDialog({
                        isOpen: false,
                        quantity: '',
                        manageStock: true,
                        selectedProducts: []
                    })}
                    onConfirm={executeStockUpdate}
                    title="Update Stock Quantity"
                    confirmText="Update Stock"
                    confirmButtonClass="btn-primary"
                >
                    <div style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '12px' }}>
                            Updating stock for <strong>{selected.length} selected products</strong>
                        </p>

                        {/* Show current stock info */}
                        {stockUpdateDialog.selectedProducts.length > 0 && (
                            <div style={{
                                background: '#f7fafc',
                                padding: '12px',
                                borderRadius: '6px',
                                marginBottom: '16px',
                                fontSize: '13px'
                            }}>
                                <div style={{ marginBottom: '8px', fontWeight: '600', color: '#2d3748' }}>
                                    Current Stock Status:
                                </div>
                                {stockUpdateDialog.selectedProducts.slice(0, 3).map(product => (
                                    <div key={product.id} style={{
                                        display: 'flex',
                                        justifyContent: 'space-between',
                                        padding: '4px 0',
                                        color: '#4a5568'
                                    }}>
                                        <span>{product.name}</span>
                                        <span style={{ fontWeight: '500' }}>
                                            {product.manage_stock
                                                ? `${product.stock_quantity || 0} units`
                                                : 'Not managed'}
                                        </span>
                                    </div>
                                ))}
                                {stockUpdateDialog.selectedProducts.length > 3 && (
                                    <div style={{ color: '#718096', fontSize: '12px', marginTop: '4px' }}>
                                        +{stockUpdateDialog.selectedProducts.length - 3} more products
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Manage Stock Checkbox */}
                        <div style={{ marginBottom: '12px' }}>
                            <label style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px',
                                cursor: 'pointer',
                                fontSize: '14px'
                            }}>
                                <input
                                    type="checkbox"
                                    checked={stockUpdateDialog.manageStock}
                                    onChange={(e) => setStockUpdateDialog({
                                        ...stockUpdateDialog,
                                        manageStock: e.target.checked
                                    })}
                                    style={{ cursor: 'pointer' }}
                                />
                                <span>Enable stock management for selected products</span>
                            </label>
                        </div>

                        {/* Stock Quantity Input */}
                        <div>
                            <label style={{
                                display: 'block',
                                marginBottom: '6px',
                                fontSize: '14px',
                                fontWeight: '500',
                                color: '#2d3748'
                            }}>
                                New Stock Quantity:
                            </label>
                            <input
                                type="number"
                                min="0"
                                className="form-control"
                                placeholder="Enter quantity"
                                value={stockUpdateDialog.quantity}
                                onChange={(e) => setStockUpdateDialog({
                                    ...stockUpdateDialog,
                                    quantity: e.target.value
                                })}
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter' && stockUpdateDialog.manageStock) {
                                        executeStockUpdate();
                                    }
                                }}
                                disabled={!stockUpdateDialog.manageStock}
                                autoFocus
                                style={{ width: '100%' }}
                            />
                            {!stockUpdateDialog.manageStock && (
                                <p style={{
                                    fontSize: '12px',
                                    color: '#e53e3e',
                                    marginTop: '6px',
                                    marginBottom: '0'
                                }}>
                                    Please enable stock management to set quantity
                                </p>
                            )}
                        </div>
                    </div>
                </ConfirmDialog>

            </div>
        </div>
    );
};

// Product View Modal Component
const ProductViewModal = ({ product, onClose }) => {
    if (!product) return null;

    const formatCurrency = (amount, currency = 'USD') => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency
        }).format(amount);
    };

    const [selectedImage, setSelectedImage] = React.useState(0);

    // Prepare gallery images
    const galleryImages = [];
    if (product.images && product.images.length > 0) {
        product.images.forEach(img => {
            if (img.src) {
                galleryImages.push(img.src);
            }
        });
    } else if (product.image) {
        galleryImages.push(product.image);
    }

    const featuredImage = galleryImages[selectedImage] || null;

    // Debug: Log product data
    console.log('Product Data:', {
        name: product.name,
        totalImages: galleryImages.length,
        hasShortDesc: !!product.short_description,
        hasDescription: !!product.description,
        shortDescLength: product.short_description?.length || 0,
        descLength: product.description?.length || 0
    });

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content product-single-page" onClick={(e) => e.stopPropagation()}>
                <button type="button" className="modal-close-btn" onClick={onClose}>
                    ✕
                </button>

                <div className="product-single-container">
                    {/* Left Side - Featured Image & Gallery */}
                    <div className="product-image-section">
                        <div className="featured-image">
                            {featuredImage ? (
                                <img src={featuredImage} alt={product.name} />
                            ) : (
                                <div className="no-image">
                                    <span>📦</span>
                                    <p>No image</p>
                                </div>
                            )}
                        </div>

                        {/* Gallery Thumbnails - Show if more than 1 image */}
                        {galleryImages.length > 1 && (
                            <div className="gallery-thumbnails">
                                {galleryImages.map((img, index) => (
                                    <div
                                        key={index}
                                        className={`thumbnail ${selectedImage === index ? 'active' : ''}`}
                                        onClick={() => setSelectedImage(index)}
                                    >
                                        <img src={img} alt={`${product.name} ${index + 1}`} />
                                    </div>
                                ))}
                            </div>
                        )}

                        {/* Descriptions Below Gallery */}
                        {product.short_description && product.short_description.trim() !== '' && (
                            <div className="description-box">
                                <div dangerouslySetInnerHTML={{ __html: product.short_description }} />
                            </div>
                        )}

                        {product.description && product.description.trim() !== '' && (
                            <div className="description-box">
                                <div dangerouslySetInnerHTML={{ __html: product.description }} />
                            </div>
                        )}
                    </div>

                    {/* Right Side - Product Info */}
                    <div className="product-info">
                        {/* Product Title & Meta */}
                        <div className="product-header">
                            <h1>{product.name}</h1>
                            <div className="product-meta">
                                <span className={`status-tag ${product.status}`}>{product.status}</span>
                                {product.featured && <span className="featured-tag">⭐ Featured</span>}
                                <span className="sku-tag">SKU: {product.sku || 'N/A'}</span>
                            </div>
                        </div>

                        {/* Price */}
                        <div className="product-price">
                            {product.sale_price ? (
                                <>
                                    <span className="sale-price">{formatCurrency(product.sale_price)}</span>
                                    <span className="regular-price">{formatCurrency(product.price)}</span>
                                    <span className="discount">
                                        Save {Math.round(((product.price - product.sale_price) / product.price) * 100)}%
                                    </span>
                                </>
                            ) : (
                                <span className="current-price">{product.price ? formatCurrency(product.price) : 'N/A'}</span>
                            )}
                        </div>

                        {/* Stock Status */}
                        <div className="product-stock">
                            <span className={`stock-badge ${product.stock_status}`}>
                                {product.stock_status === 'instock' ? '✓ In Stock' :
                                    product.stock_status === 'outofstock' ? '✗ Out of Stock' :
                                        '⚠ On Backorder'}
                            </span>
                            {product.manage_stock && product.stock_quantity > 0 && (
                                <span className="stock-qty">{product.stock_quantity} units available</span>
                            )}
                        </div>

                        {/* Product Details Table */}
                        <div className="product-details-table">
                            <h3>Product Details</h3>
                            <table>
                                <tbody>
                                    <tr>
                                        <td>Product ID</td>
                                        <td>#{product.id}</td>
                                    </tr>
                                    <tr>
                                        <td>Type</td>
                                        <td>{product.type || 'Simple'}</td>
                                    </tr>
                                    {product.weight && (
                                        <tr>
                                            <td>Weight</td>
                                            <td>{product.weight} kg</td>
                                        </tr>
                                    )}
                                    {product.dimensions && (
                                        <tr>
                                            <td>Dimensions</td>
                                            <td>{product.dimensions.length} × {product.dimensions.width} × {product.dimensions.height} cm</td>
                                        </tr>
                                    )}
                                    <tr>
                                        <td>Date Created</td>
                                        <td>{new Date(product.date_created).toLocaleDateString()}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        {/* Categories & Tags */}
                        {((product.categories && product.categories.length > 0) || (product.tags && product.tags.length > 0)) && (
                            <div className="product-taxonomy">
                                {product.categories && product.categories.length > 0 && (
                                    <div className="tax-group">
                                        <strong>Categories:</strong>
                                        <div className="tax-items">
                                            {product.categories.map((cat, i) => (
                                                <span key={i} className="tax-item category">{cat.name}</span>
                                            ))}
                                        </div>
                                    </div>
                                )}
                                {product.tags && product.tags.length > 0 && (
                                    <div className="tax-group">
                                        <strong>Tags:</strong>
                                        <div className="tax-items">
                                            {product.tags.map((tag, i) => (
                                                <span key={i} className="tax-item tag">{tag.name}</span>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Action Buttons */}
                        <div className="product-actions">
                            <button
                                className="btn btn-primary btn-lg"
                                onClick={() => {
                                    onClose();
                                    window.location.href = `/products/edit/${product.id}`;
                                }}
                            >
                                ✏️ Edit Product
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};



export default Products;