﻿class Catalog extends React.Component {
    constructor(props) {
        super(props);

        // Mantener una copia en memoria sin reactividad si se desea, o inicializar null
        this.allProds = [];

        this.state = {
            isLoaded: false,
            taxIncluded: true,
            excludeTax: false,
            products: [],
            enterprises: [],
            branchs: [],
            categories: [],
            viewBy: [
                { id: 'all', name: 'Todos' },
                { id: 'stk', name: 'Con Inventario' },
                { id: 'noStk', name: 'Sin Inventario' },
                { id: 'noShow', name: 'Ocultar Inventario' }
            ],
            enterpriseName: '',
            selectedEnterprise: 1,
            selectedBranch: -2,
            selectedCat: -2,
            hasStock: 'all',
            showStock: true,
            searchValue: '',
            qtyFilter: 0
        };
    }

    componentDidMount = async () => {
        try {
            const entsRes = await fetch("/global/getEnterprise", { method: 'post' });
            const ents = await entsRes.json();
            const defaultEntId = ents.length > 0 ? ents[0].enterpriseID : 1;

            this.setState({
                enterprises: ents,
                selectedEnterprise: defaultEntId
            }, () => {
                this.loadEnterpriseData(defaultEntId);
               // this.handleFilterProducts();
            });
        } catch (error) {
            console.error("Error al cargar empresas:", error);
        }
    }

    // Carga sucursales, categorías y datos de la empresa seleccionada
    loadEnterpriseData = async (entId) => {
        try {
            const [branchRes, entDataRes, catRes] = await Promise.all([
                fetch("/global/getBranchs?entId=" + entId, { method: 'post' }),
                fetch("/global/GetEnterpriseData?entId=" + entId, { method: 'post' }),
                fetch("/global/getParentCategories?entId=" + entId, { method: 'post' })
            ]);

            const branchs = await branchRes.json();
            const entData = await entDataRes.json();
            const categories = await catRes.json();

            this.setState({
                branchs: branchs,
                taxIncluded: entData.taxIncluded == 1,
                categories: categories
            });
        } catch (error) {
            console.error("Error al cargar datos asociados a la empresa:", error);
        }
    }

    // Método centralizado para filtrar productos
    handleFilterProducts = async () => {
        this.setState({ products: [], isLoaded: false });

        const { selectedEnterprise, selectedBranch, selectedCat, searchValue, hasStock, showStock } = this.state;
        let url = '';
        // hasStock = hasStock == 'noShow' ? 'All' : hasStock
        let newHastStock = !showStock ? 'all' : hasStock
        if (selectedCat != -2 && selectedCat != -1) {
            url = selectedBranch == -2
                ? `/global/getProductsForCatalogCategory?entId=${selectedEnterprise}&catId=${selectedCat}&search=${searchValue}&hasStok=${newHastStock}`
                : `/global/getProductsForBranchCatalogCategory?entId=${selectedEnterprise}&branchId=${selectedBranch}&catId=${selectedCat}&search=${searchValue}&hasStok=${newHastStock}`;
        } else {
            url = selectedBranch == -2
                ? `/global/getProductsForCatalog?entId=${selectedEnterprise}&search=${searchValue}&hasStok=${newHastStock}`
                : `/global/getProductsBranchsForCatalog?entId=${selectedEnterprise}&branchId=${selectedBranch}&search=${searchValue}&hasStok=${newHastStock}`;
        }

        try {

            const res = await fetch(url, { method: 'post' });
            const data = await res.json();

            this.allProds = this.sortProductsByName(data);
            this.setState({ products: this.sortProductsByName(data), isLoaded: true });
        } catch (err) {
            console.error("Error al obtener productos:", err);
            this.setState({ isLoaded: true });
        }

    }

    sortProductsByName(items, ascending = true) {
        if (!Array.isArray(items)) return [];

        return [...items].sort((a, b) => {
            const nameA = a?.productName ?? '';
            const nameB = b?.productName ?? '';

            const comparacion = nameA.localeCompare(nameB, 'es', {
                sensitivity: 'base'
            });

            return ascending ? comparacion : -comparacion;
        });
    }


    // Filtro en memoria por cantidad de stock
    handleStockQtyFilter = (minStock) => {
        const val = Number(minStock) || 0;
        const filtered = this.allProds.filter(item => (item.stock || 0) >= val);
        this.setState({ products: filtered });
    }

    // Ajuste de impuestos (inmutable)
    changeTaxPrices = (e) => {
        const isExempt = e.target.checked;
        const updatedProducts = this.state.products.map(product => {
            const tx = product.taxPercent || 0;
            return {
                ...product,
                prices: product.prices.map(priceObj => ({
                    ...priceObj,
                    price: isExempt ? (priceObj.price / (1 + tx)) : (priceObj.price * (1 + tx))
                }))
            };
        });

        this.setState({ products: updatedProducts, excludeTax: isExempt });
    }

    render() {
        const {
            isLoaded,
            taxIncluded,
            products,
            enterprises,
            branchs,
            categories,
            viewBy,
            selectedEnterprise,
            selectedBranch,
            selectedCat,
            hasStock,
            showStock,
            searchValue,
            qtyFilter
        } = this.state;

        return (
            <div className="col-lg-12 cat">
                <div className="modal-header" style={{
                    backgroundColor: '#f8fafc',
                    borderBottom: '1px solid #e2e8f0',
                    padding: '16px 20px',
                    borderTopLeftRadius: '6px',
                    borderTopRightRadius: '6px'
                }}>
                    <div className="row" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '10px 0' }}>

                        {/* Botón Imprimir */}
                        <div className="col-xs-12 col-sm-2 col-md-1">
                            <button
                                type="button"
                                id="btnPrint"
                                className="btn btn-primary btn-block"
                                style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: '500' }}
                                onClick={() => window.print()}
                            >
                                <span className="glyphicon glyphicon-print" style={{ marginRight: '6px' }}></span>
                                Imprimir
                            </button>
                        </div>

                        {/* Búsqueda y Checkbox de Impuesto */}
                        <div className="col-xs-12 col-sm-4 col-md-3">
                            <div className="input-group">
                                <input
                                    type="text"
                                    className="form-control"
                                    placeholder="Buscar producto..."
                                    value={searchValue}
                                    onChange={(e) => this.setState({ searchValue: e.target.value })}
                                    onKeyDown={(e) => { if (e.key === 'Enter') this.handleFilterProducts(); }}
                                />
                                <span className="input-group-btn">
                                    <button
                                        type="button"
                                        id="btnSearch"
                                        className="btn btn-default"
                                        onClick={this.handleFilterProducts}
                                        style={{ borderColor: '#cbd5e1', color: '#475569' }}
                                    >
                                        <span className="glyphicon glyphicon-search"></span>
                                    </button>
                                </span>
                            </div>

             
                        </div>

                        {/* Filtro Empresa */}
                        <div className="col-xs-12 col-sm-3 col-md-2">
                            <div className="row">
                            <select
                                className="form-control"
                                value={selectedEnterprise}
                                onChange={(e) => {
                                    const val = e.target.value;
                                    this.setState({ selectedEnterprise: val, selectedBranch: -2, selectedCat: -2 }, () => {
                                        this.loadEnterpriseData(val);
                                        //this.handleFilterProducts();
                                    });
                                }}
                            >
                                {enterprises.map((ent) => (
                                    <option key={ent.enterpriseID} value={ent.enterpriseID}>
                                        {ent.enterpriseName}
                                    </option>
                                ))}
                                </select>
                            </div>
                            <div className="row">
                                {this.taxIncluded && (
                                    <div style={{ marginTop: '6px', display: 'flex', alignItems: 'center' }}>
                                        <label htmlFor="excludetax" style={{ fontSize: '12px', color: '#64748b', cursor: 'pointer', margin: 0, fontWeight: 'normal' }}>
                                            <input
                                                type="checkbox"
                                                id="excludetax"
                                                style={{ marginRight: '6px', marginTop: 0 }}
                                                onChange={this.changeTaxPrices(this)}
                                            />
                                            Precios sin Impuesto
                                        </label>
                                    </div>
                                )}
                                </div>
                        </div>
                       

                        {/* Filtro Sucursales */}
                        <div className="col-xs-12 col-sm-3 col-md-2">
                            <select
                                className="form-control"
                                value={selectedBranch}
                                onChange={(e) => {
                                    this.setState({ selectedBranch: e.target.value } /*this.handleFilterProducts*/);
                                }}
                            >
                                <option value={-2}>Todas las tiendas</option>
                                {branchs.map((br) => (
                                    <option key={br.branchId} value={br.branchId}>{br.shortName}</option>
                                ))}
                            </select>
                        </div>

                        {/* Filtro Categorías */}
                        <div className="col-xs-12 col-sm-3 col-md-2">
                            <select
                                className="form-control"
                                value={selectedCat}
                                onChange={(e) => {
                                    this.setState({ selectedCat: e.target.value }/*, this.handleFilterProducts*/);
                                }}
                            >
                                <option value={-2}>Todas las categorias</option>
                                {categories.map((cat) => (
                                    <option key={cat.categoryID} value={cat.categoryID}>{cat.categoryName}</option>
                                ))}
                            </select>
                        </div>

                        {/* Filtro Stock / Vista */}
                        <div className="col-xs-12 col-sm-3 col-md-1">
                            <select
                                className="form-control"
                                value={hasStock}
                                onChange={(e) => {
                                    const val = e.target.value;
                                    this.setState({
                                        hasStock: val,
                                        showStock: val !== 'noShow'
                                    }, () => {
                                        this.handleFilterProducts();
                                    });
                                }}
                            >
                                {viewBy.map((v) => (
                                    <option key={v.id} value={v.id}>{v.name}</option>
                                ))}
                            </select>
                        </div>

                        {/* Input Cantidad de Stock */}
                        {hasStock === 'stk' && (
                            <div className="col-xs-12 col-sm-2 col-md-1">
                                <input
                                    type="number"
                                    className="form-control"
                                    value={qtyFilter}
                                    onChange={(e) => {
                                        const val = e.target.value;
                                        this.setState({ qtyFilter: val });
                                        this.handleStockQtyFilter(val);
                                    }}
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') this.handleStockQtyFilter(qtyFilter);
                                    }}
                                />
                            </div>
                        )}

                    </div>
                </div>

                <div className="cover" id="cover">
                    <EnterpriseData key={selectedEnterprise} idEnt={selectedEnterprise} />
                </div>

                {!isLoaded && (
                    <div style={{ display: "flex", justifyContent: "center", alignItems: "center", padding: '20px' }}>
                        <img src='/images/waitGiff.gif' alt="Cargando..." />
                    </div>
                )}

                <div className="row filas">
                    {products.map((prod, i) => (
                        <ProductCard
                            key={prod.productID}
                            product={prod}
                            displayStock={showStock}
                            enterpriseId={selectedEnterprise}
                            prices={prod.prices}
                            index={i}
                        />
                    ))}
                </div>

                <div className="waterMark" id="waterMark">
                    <EnterpriseDataWaterMark key="waterMxx" idEnt={selectedEnterprise} />
                </div>
            </div>
        );
    }
}