import React, { useState, useEffect } from 'react';

const ProductSelector = ({
    productSource,
    selectedProducts,
    selectedCategories,
    selectedTags,
    selectedBrands,
    selectedAttribute,
    selectedAttributeTerms,
    onProductsChange,
    onCategoriesChange,
    onTagsChange,
    onBrandsChange,
    onAttributeChange,
    onAttributeTermsChange
}) => {
    const [products, setProducts] = useState([]);
    const [categories, setCategories] = useState([]);
    const [tags, setTags] = useState([]);
    const [brands, setBrands] = useState([]);
    const [attributes, setAttributes] = useState([]);
    const [attributeTerms, setAttributeTerms] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('');
    const [loading, setLoading] = useState(false);
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const [showSelectedProducts, setShowSelectedProducts] = useState(false);
    const [selectedProductsDetails, setSelectedProductsDetails] = useState([]);

    useEffect(() => {
        if (productSource === 'specific') {
            loadProducts();
        }
        loadCategories();
        if (productSource === 'tag') {
            loadTags();
        }
        if (productSource === 'brand') {
            loadBrands();
        }
        if (productSource === 'attribute') {
            loadAttributes();
        }
    }, [productSource]);

    useEffect(() => {
        if (selectedAttribute && productSource === 'attribute') {
            loadAttributeTerms();
        }
    }, [selectedAttribute, productSource]);

    const loadProducts = async (page = 1) => {
        try {
            setLoading(true);
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_products',
                    nonce: proddispAdmin.nonce,
                    search: searchTerm,
                    category: selectedCategory,
                    page: page,
                    per_page: 20
                })
            });

            const data = await response.json();
            if (data.success) {
                setProducts(data.data.products || []);
                setCurrentPage(data.data.pagination?.current_page || 1);
                setTotalPages(data.data.pagination?.total_pages || 1);
            }
        } catch (error) {
            console.error('Error loading products:', error);
        } finally {
            setLoading(false);
        }
    };

    const loadCategories = async () => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_categories',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            if (data.success) {
                setCategories(data.data.categories || []);
            }
        } catch (error) {
            console.error('Error loading categories:', error);
        }
    };

    const loadTags = async () => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_tags',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            if (data.success) {
                setTags(data.data.tags || []);
            }
        } catch (error) {
            console.error('Error loading tags:', error);
        }
    };

    const loadBrands = async () => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_brands',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            if (data.success) {
                setBrands(data.data.brands || []);
            }
        } catch (error) {
            console.error('Error loading brands:', error);
        }
    };

    const loadAttributes = async () => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_attributes',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            if (data.success) {
                setAttributes(data.data.attributes || []);
            }
        } catch (error) {
            console.error('Error loading attributes:', error);
        }
    };

    const loadAttributeTerms = async () => {
        if (!selectedAttribute) return;

        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_attribute_terms',
                    nonce: proddispAdmin.nonce,
                    attribute: selectedAttribute
                })
            });

            const data = await response.json();
            if (data.success) {
                setAttributeTerms(data.data.terms || []);
            }
        } catch (error) {
            console.error('Error loading attribute terms:', error);
        }
    };

    const loadSelectedProductsDetails = async () => {
        if (selectedProducts.length === 0) {
            setSelectedProductsDetails([]);
            return;
        }

        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_products_by_ids',
                    nonce: proddispAdmin.nonce,
                    product_ids: selectedProducts.join(',')
                })
            });

            const data = await response.json();
            if (data.success) {
                setSelectedProductsDetails(data.data.products || []);
            }
        } catch (error) {
            console.error('Error loading selected products details:', error);
        }
    };

    // Load selected products details when showSelectedProducts is toggled
    useEffect(() => {
        if (showSelectedProducts && selectedProducts.length > 0) {
            loadSelectedProductsDetails();
        }
    }, [showSelectedProducts, selectedProducts]);

    useEffect(() => {
        if (productSource === 'specific') {
            const debounceTimer = setTimeout(() => {
                loadProducts(1);
            }, 300);

            return () => clearTimeout(debounceTimer);
        }
    }, [searchTerm, selectedCategory, productSource]);

    const handleProductToggle = (productId) => {
        const newProducts = selectedProducts.includes(productId)
            ? selectedProducts.filter(id => id !== productId)
            : [...selectedProducts, productId];

        onProductsChange(newProducts);
    };

    const handleSelectAll = () => {
        // Add current page products to existing selection instead of replacing
        const currentPageProductIds = products.map(p => p.id);
        const newProducts = [...new Set([...selectedProducts, ...currentPageProductIds])];
        onProductsChange(newProducts);
    };

    const handleSelectAllCurrentPage = () => {
        // Select all products on current page only
        const currentPageProductIds = products.map(p => p.id);
        const newProducts = [...new Set([...selectedProducts, ...currentPageProductIds])];
        onProductsChange(newProducts);
    };

    const handleClearAllCurrentPage = () => {
        // Clear only current page products from selection
        const currentPageProductIds = products.map(p => p.id);
        const newProducts = selectedProducts.filter(id => !currentPageProductIds.includes(id));
        onProductsChange(newProducts);
    };

    const handleClearAll = () => {
        // Clear all selected products
        onProductsChange([]);
    };

    const handleCategoryToggle = (categoryId) => {
        const newCategories = selectedCategories.includes(categoryId)
            ? selectedCategories.filter(id => id !== categoryId)
            : [...selectedCategories, categoryId];

        onCategoriesChange(newCategories);
    };

    const handleTagToggle = (tagId) => {
        const newTags = selectedTags.includes(tagId)
            ? selectedTags.filter(id => id !== tagId)
            : [...selectedTags, tagId];

        onTagsChange(newTags);
    };

    const handleBrandToggle = (brandId) => {
        const newBrands = selectedBrands.includes(brandId)
            ? selectedBrands.filter(id => id !== brandId)
            : [...selectedBrands, brandId];

        onBrandsChange(newBrands);
    };

    const handleAttributeTermToggle = (termId) => {
        const newTerms = selectedAttributeTerms.includes(termId)
            ? selectedAttributeTerms.filter(id => id !== termId)
            : [...selectedAttributeTerms, termId];

        onAttributeTermsChange(newTerms);
    };

    const renderSpecificProducts = () => (
        <div className="proddisp-specific-products">
            <div className="proddisp-product-filters">
                <input
                    type="search"
                    placeholder="Search products..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="proddisp-search-input"
                />
                <select
                    value={selectedCategory}
                    onChange={(e) => setSelectedCategory(e.target.value)}
                >
                    <option value="">All Categories</option>
                    {categories.map(category => (
                        <option key={category.id} value={category.id}>
                            {category.name}
                        </option>
                    ))}
                </select>
            </div>

            <div className="proddisp-bulk-actions">
                <button
                    className="button"
                    onClick={handleSelectAllCurrentPage}
                    disabled={loading}
                    title="Select all products on current page"
                >
                    Select Page
                </button>
                <button
                    className="button"
                    onClick={handleClearAllCurrentPage}
                    disabled={loading}
                    title="Clear selection for current page"
                >
                    Clear Page
                </button>
                <button
                    className="button"
                    onClick={handleClearAll}
                    title="Clear all selected products"
                >
                    Clear All
                </button>
                
            </div>
            {/* Selected product  */}
            <div className="prodisp-selected-product">
                <span className="selected-count">
                    <strong>{selectedProducts.length} selected</strong>
                    {totalPages > 1 && (
                        <span className="page-selection-info">
                            {' '}({products.filter(p => selectedProducts.includes(p.id)).length} on this page)
                        </span>
                    )}
                </span>
                {selectedProducts.length > 0 && (
                    <button
                        className="button button-secondary"
                        onClick={() => setShowSelectedProducts(!showSelectedProducts)}
                        title="Toggle view of all selected products"
                    >
                        {showSelectedProducts ? 'Hide' : 'View'}
                    </button>
                )}
            </div>
            
            {loading ? (
                <div className="proddisp-loading">
                    <div className="spinner"></div>
                    <p>Loading products...</p>
                </div>
            ) : (
                <>
                    {selectedProducts.length > 0 && totalPages > 1 && (
                        <div className="selected-products-summary">
                            <h4>Selected Products Summary</h4>
                            <p>
                                You have selected <strong>{selectedProducts.length} products</strong> total.
                                {products.filter(p => selectedProducts.includes(p.id)).length > 0 && (
                                    <span> ({products.filter(p => selectedProducts.includes(p.id)).length} visible on this page)</span>
                                )}
                            </p>
                            {selectedProducts.length > products.filter(p => selectedProducts.includes(p.id)).length && (
                                <p className="other-pages-notice">
                                    <em>Some selected products are on other pages and not currently visible.</em>
                                </p>
                            )}
                        </div>
                    )}

                    {showSelectedProducts && selectedProducts.length > 0 && (
                        <div className="selected-products-view">
                            <h4>All Selected Products ({selectedProducts.length})</h4>
                            <div className="selected-products-grid">
                                {selectedProductsDetails.length > 0 ? selectedProductsDetails.map(product => (
                                    <div key={product.id} className="selected-product-item">
                                        <div className="product-info">
                                            {product.image && (
                                                <img
                                                    src={product.image}
                                                    alt={product.name}
                                                    className="product-thumbnail"
                                                />
                                            )}
                                            <div className="product-details">
                                                <h5 className="product-name">{product.name}</h5>
                                                <span className="product-price" dangerouslySetInnerHTML={{ __html: product.price }}></span>
                                            </div>
                                        </div>
                                        <button
                                            className="remove-product"
                                            onClick={() => handleProductToggle(product.id)}
                                            title="Remove from selection"
                                        >
                                            ×
                                        </button>
                                    </div>
                                )) : (
                                    <div className="loading-selected">
                                        <div className="spinner"></div>
                                        <p>Loading selected products...</p>
                                    </div>
                                )}
                            </div>
                        </div>
                    )}

                    <div className="proddisp-product-grid">
                        {products.length > 0 ? products.map(product => (
                            <div
                                key={product.id}
                                className={`proddisp-product-item ${selectedProducts.includes(product.id) ? 'selected' : ''}`}
                            >
                                <label>
                                    <input
                                        type="checkbox"
                                        checked={selectedProducts.includes(product.id)}
                                        onChange={() => handleProductToggle(product.id)}
                                    />
                                    <div className="product-info">
                                        {product.image && (
                                            <img
                                                src={product.image}
                                                alt={product.name}
                                                className="product-thumbnail"
                                            />
                                        )}
                                        <div className="product-details">
                                            <h4 className="product-name">{product.name}</h4>
                                            <span className="product-price" dangerouslySetInnerHTML={{ __html: product.price }}></span>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        )) : (
                            <div className="no-products">
                                <p>No products found. Try adjusting your search or category filter.</p>
                            </div>
                        )}
                    </div>

                    {totalPages > 1 && (
                        <div className="proddisp-pagination">
                            <button
                                className="button"
                                onClick={() => loadProducts(currentPage - 1)}
                                disabled={currentPage <= 1}
                            >
                                Previous
                            </button>
                            <span className="page-info">
                                Page {currentPage} of {totalPages}
                            </span>
                            <button
                                className="button"
                                onClick={() => loadProducts(currentPage + 1)}
                                disabled={currentPage >= totalPages}
                            >
                                Next
                            </button>
                        </div>
                    )}
                </>
            )}
        </div>
    );

    const renderCategorySelection = () => (
        <div className="proddisp-category-selection">
            <div className="setting-group">
                <label>Select Categories</label>
                <p className="description">Choose one or more categories to display products from.</p>
                <div className="proddisp-category-grid">
                    {categories.map(category => (
                        <div key={category.id} className="category-item">
                            <label>
                                <input
                                    type="checkbox"
                                    checked={selectedCategories.includes(category.id.toString())}
                                    onChange={() => handleCategoryToggle(category.id.toString())}
                                />
                                <span className="category-name">{category.name}</span>
                                <span className="category-count">({category.count} products)</span>
                            </label>
                        </div>
                    ))}
                </div>
                {selectedCategories.length > 0 && (
                    <div className="selected-summary">
                        <strong>{selectedCategories.length} categories selected</strong>
                    </div>
                )}
            </div>
        </div>
    );

    const renderTagSelection = () => (
        <div className="proddisp-tag-selection">
            {!proddispAdmin.isProActive ? (
                <div className="pro-feature-notice">
                    <h4>🔒 Pro Feature</h4>
                    <p>Tag-based product selection is available in the Pro version.</p>
                    <a href="#" className="button button-primary">Upgrade to Pro</a>
                </div>
            ) : (
                <div className="setting-group">
                    <label>Select Tags</label>
                    <p className="description">Choose one or more tags to display products from.</p>
                    <div className="proddisp-tag-grid">
                        {tags.map(tag => (
                            <div key={tag.id} className="tag-item">
                                <label>
                                    <input
                                        type="checkbox"
                                        checked={selectedTags.includes(tag.id.toString())}
                                        onChange={() => handleTagToggle(tag.id.toString())}
                                    />
                                    <span className="tag-name">{tag.name}</span>
                                    <span className="tag-count">({tag.count} products)</span>
                                </label>
                            </div>
                        ))}
                    </div>
                    {selectedTags.length > 0 && (
                        <div className="selected-summary">
                            <strong>{selectedTags.length} tags selected</strong>
                        </div>
                    )}
                </div>
            )}
        </div>
    );

    const renderBrandSelection = () => (
        <div className="proddisp-brand-selection">
            {!proddispAdmin.isProActive ? (
                <div className="pro-feature-notice">
                    <h4>🔒 Pro Feature</h4>
                    <p>Brand-based product selection is available in the Pro version.</p>
                    <a href="#" className="button button-primary">Upgrade to Pro</a>
                </div>
            ) : (
                <div className="setting-group">
                    <label>Select Brands</label>
                    <p className="description">Choose one or more brands to display products from.</p>
                    <div className="proddisp-brand-grid">
                        {brands.map(brand => (
                            <div key={brand.id} className="brand-item">
                                <label>
                                    <input
                                        type="checkbox"
                                        checked={selectedBrands.includes(brand.id.toString())}
                                        onChange={() => handleBrandToggle(brand.id.toString())}
                                    />
                                    <span className="brand-name">{brand.name}</span>
                                    <span className="brand-count">({brand.count} products)</span>
                                </label>
                            </div>
                        ))}
                    </div>
                    {selectedBrands.length > 0 && (
                        <div className="selected-summary">
                            <strong>{selectedBrands.length} brands selected</strong>
                        </div>
                    )}
                </div>
            )}
        </div>
    );

    const renderAttributeSelection = () => (
        <div className="proddisp-attribute-selection">
            {!proddispAdmin.isProActive ? (
                <div className="pro-feature-notice">
                    <h4>🔒 Pro Feature</h4>
                    <p>Attribute-based product selection is available in the Pro version.</p>
                    <a href="#" className="button button-primary">Upgrade to Pro</a>
                </div>
            ) : (
                <div className="setting-group">
                    <label htmlFor="attribute-select">Select Attribute</label>
                    <select
                        id="attribute-select"
                        value={selectedAttribute}
                        onChange={(e) => {
                            onAttributeChange(e.target.value);
                            onAttributeTermsChange([]); // Clear selected terms when attribute changes
                        }}
                        className="regular-text"
                    >
                        <option value="">Choose an attribute...</option>
                        {attributes.map(attribute => (
                            <option key={attribute.id} value={attribute.slug}>
                                {attribute.name}
                            </option>
                        ))}
                    </select>

                    {selectedAttribute && attributeTerms.length > 0 && (
                        <div className="attribute-terms">
                            <label>Select {attributes.find(a => a.slug === selectedAttribute)?.name} Values</label>
                            <div className="proddisp-term-grid">
                                {attributeTerms.map(term => (
                                    <div key={term.id} className="term-item">
                                        <label>
                                            <input
                                                type="checkbox"
                                                checked={selectedAttributeTerms.includes(term.id.toString())}
                                                onChange={() => handleAttributeTermToggle(term.id.toString())}
                                            />
                                            <span className="term-name">{term.name}</span>
                                            <span className="term-count">({term.count} products)</span>
                                        </label>
                                    </div>
                                ))}
                            </div>
                            {selectedAttributeTerms.length > 0 && (
                                <div className="selected-summary">
                                    <strong>{selectedAttributeTerms.length} values selected</strong>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            )}
        </div>
    );

    const renderAllProducts = () => (
        <div className="proddisp-all-products">
            <div className="setting-group">
                <h4>All Products Display</h4>
                <p className="description">
                    This will display all published products from your store.
                    Use the Settings tab to configure ordering and limits.
                </p>
                <div className="all-products-info">
                    <div className="info-item">
                        <span className="dashicons dashicons-products"></span>
                        <span>All published products will be displayed</span>
                    </div>
                    <div className="info-item">
                        <span className="dashicons dashicons-admin-settings"></span>
                        <span>Configure display options in the Settings tab</span>
                    </div>
                    <div className="info-item">
                        <span className="dashicons dashicons-filter"></span>
                        <span>Products will respect your ordering and limit settings</span>
                    </div>
                </div>
            </div>
        </div>
    );

    const renderContent = () => {
        switch (productSource) {
            case 'specific':
                return renderSpecificProducts();
            case 'category':
                return renderCategorySelection();
            case 'tag':
                return renderTagSelection();
            case 'brand':
                return renderBrandSelection();
            case 'attribute':
                return renderAttributeSelection();
            default:
                return renderAllProducts();
        }
    };

    return (
        <div className="proddisp-product-selector">
            <div className="proddisp-selection-content">
                {renderContent()}
            </div>
        </div>
    );
};

export default ProductSelector;