"use client";

import { useEffect, useState, useCallback } from "react";
import dynamic from "next/dynamic";
import PageHeading from "@/components/common/PageHeading";
import { useT } from "@/context/I18nContext";

const DynamicShopFullwidth = dynamic(() => import("@/components/shop/ShopFullwidth"), { ssr: false });

export default function ToateProdusele() {
	const { t } = useT();

	const [productsData, setProductsData] = useState([]);
	const [totalCount, setTotalCount] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [totalPages, setTotalPages] = useState(0);
	const [loading, setLoading] = useState(true);
	const [filters, setFilters] = useState({
		sort: "newest",
		minPrice: "",
		maxPrice: "",
		category: "",
		search: "",
	});

	const fetchProducts = useCallback(
		async (page = 1, currentFilters = filters) => {
			setLoading(true);
			try {
				const params = new URLSearchParams({
					page,
					limit: 32,
					...Object.fromEntries(Object.entries(currentFilters).filter(([, v]) => v !== "")),
				});

				const response = await fetch(`/api/products?${params}`);

				if (!response.ok) throw new Error("Fetch failed");

				const data = await response.json();

				setProductsData(data.products);
				setTotalCount(data.totalCount);
				setCurrentPage(data.currentPage);
				setTotalPages(data.totalPages);
			} catch (error) {
				console.error("Error loading products:", error);
			} finally {
				setLoading(false);
			}
		},
		[],
	);

	useEffect(() => {
		fetchProducts(1, filters);
	}, []);

	const handlePageChange = (newPage) => {
		fetchProducts(newPage, filters);
		window.scrollTo({ top: 0, behavior: "smooth" });
	};

	if (loading) {
		return (
			<div
				style={{
					minHeight: "400px",
					display: "flex",
					alignItems: "center",
					justifyContent: "center",
				}}>
				<p>Se încarcă produsele...</p>
			</div>
		);
	}

	return (
		<>
			<PageHeading title={`${t("toate_produsele")}: ${totalCount}`} />
			<DynamicShopFullwidth
				productsData={productsData}
				currentPage={currentPage}
				totalPages={totalPages}
				onPageChange={handlePageChange}
				onFilterChange={setFilters}
			/>
		</>
	);
}
