"use client";
import ProductGrid from "./ProductGrid";
import { useState, useEffect } from "react";
import Pagination from "../common/Pagination";
import ShopFilter from "./ShopFilter";
import Sorting from "./Sorting";

export default function ShopFullwidth({ productsData }) {
	const [gridItems, setGridItems] = useState(32);
	const [products, setProducts] = useState(productsData);
     const [filteredProducts, setFilteredProducts] = useState(productsData);
	const [finalSorted, setFinalSorted] = useState(productsData);
	const [activePage, setActivePage] = useState(1);
	const [paginatedProducts, setPaginatedProducts] = useState([]);

	useEffect(() => {
        setFinalSorted(filteredProducts);
        setActivePage(1);
     }, [filteredProducts]);

     const totalPages = Math.ceil(finalSorted.length / gridItems);

     useEffect(() => {
        const startIndex = (activePage - 1) * gridItems;
        const endIndex = startIndex + gridItems;
        setPaginatedProducts(finalSorted.slice(startIndex, endIndex));
    }, [activePage, gridItems, finalSorted]);

	const handlePageClick = (pageNumber) => {
		setActivePage(pageNumber);
          window.scrollTo({ top: 0, behaivor: "smooth" }); 
	};

	return (
		<>
			<section
				className='flat-spacing-2'
				style={{ marginLeft: "50px", marginRight: "50px" }}
			>
				<div className='container-full'>
					<div className='tf-shop-control grid-2 align-items-left'>
						<div className='tf-control-filter'>
							<a
								href='#filterShop'
								data-bs-toggle='offcanvas'
								aria-controls='offcanvasLeft'
								className='tf-btn-filter'
							>
								<span className='icon icon-filter' />
								<span className='text'>Filter</span>
							</a>
						</div>

						<div className='tf-control-sorting d-flex justify-content-end'>
							<div
								className='tf-dropdown-sort'
								data-bs-toggle='dropdown'
							>
								<Sorting
									setFinalSorted={setFinalSorted}
									products={filteredProducts} 
								/>
							</div>
						</div>
					</div>
					<div className='wrapper-control-shop'>
						<div className='meta-filter-shop' />
						<ProductGrid
							allproducts={paginatedProducts}
							gridItems={gridItems}
						/>
						{/* pagination */}
						{finalSorted.length ? (
							<ul className='tf-pagination-wrap tf-pagination-list tf-pagination-btn'>
								<Pagination
									activePage={activePage}
									handlePageClick={handlePageClick}
									totalPages={totalPages}
								/>
							</ul>
						) : (
							""
						)}
					</div>
				</div>
			</section>
			<ShopFilter products={products} setFilteredProducts={setFilteredProducts} />
		</>
	);
}
