"use client";

import { useEffect, useState, Suspense } from "react";
import Link from "next/link";

import useSWR from "swr";
import Hero from "@/components/homes/home-6/Hero";
import Features from "@/components/common/Features";
import CategoryProducts from "@/components/common/CategoryProducts";
import dynamic from "next/dynamic";

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

const fetcher = async (url) => {
	const res = await fetch(url);

	let data = null;
	try {
		data = await res.json();
	} catch (e) {
		data = null;
	}

	if (!res.ok) {
		const err = new Error("Request failed");
		err.status = res.status;
		err.data = data;
		throw err;
	}

	return data;
};

function LoadingSkeleton() {
	return (
		<div className='container py-5'>
			<div className='animate-pulse'>
				<div className='h-4 bg-gray-300 rounded w-3/4 mb-4'></div>
				<div className='h-4 bg-gray-300 rounded w-1/2 mb-4'></div>
				<div className='h-32 bg-gray-300 rounded mb-4'></div>
			</div>
		</div>
	);
}

export default function PageContent({ params, searchParams }) {
	const { slug } = params || {};
	const searchQuery = searchParams?.q || null;

	const [pageType, setPageType] = useState(null);

	// slug helpers
	const isMultiLevel = Array.isArray(slug) && slug.length > 1;
	const isSingleLevel = Array.isArray(slug) && slug.length === 1;
	const slugString = Array.isArray(slug) ? slug[slug.length - 1] : slug;
	const slugPath = Array.isArray(slug) ? slug.join("/") : slug;

	useEffect(() => {
		setPageType(null);
	}, [slugPath, searchQuery]);

	const { data: multiLevelCategoryData, error: multiLevelCategoryError } = useSWR(
		isMultiLevel ? `/api/categories/${slugPath}` : null,
		fetcher,
		{ revalidateOnFocus: false, shouldRetryOnError: false },
	);

	const {
		data: singleCategoryData,
		error: singleCategoryError,
		isLoading: categoryLoading,
	} = useSWR(
		(isSingleLevel || (!Array.isArray(slug) && slug)) && !isMultiLevel ? `/api/categories/${slugString}` : null,
		fetcher,
		{ revalidateOnFocus: false, shouldRetryOnError: false },
	);

	const {
		data: product,
		error: productError,
		isLoading: productLoading,
	} = useSWR(
		(isSingleLevel || (!Array.isArray(slug) && slug)) && !isMultiLevel ? `/api/products/${slugString}` : null,
		fetcher,
		{ revalidateOnFocus: false, shouldRetryOnError: false },
	);

	const { data: categories, error: categoriesError } = useSWR(
		!slug && !searchQuery ? `/api/categories2` : null,
		fetcher,
		{ revalidateOnFocus: false, shouldRetryOnError: false },
	);

	const buildSearchUrl = () => {
		if (!searchQuery) return null;

		const qp = new URLSearchParams({ q: searchQuery });

		if (slug) {
			const slugArray = Array.isArray(slug) ? slug : [slug];
			if (slugArray[0]) qp.append("category", slugArray[0]);
			if (slugArray[1]) qp.append("subcategory", slugArray[1]);
			if (slugArray[2]) qp.append("thirdcategory", slugArray[2]);
		}

		return `/api/search?${qp.toString()}`;
	};

	const { data: searchResults, error: searchError } = useSWR(buildSearchUrl(), fetcher, {
		revalidateOnFocus: false,
		shouldRetryOnError: false,
	});

	useEffect(() => {
		if (searchQuery) return setPageType("search");
		if (!slug) return setPageType("homepage");

		if (isMultiLevel) {
			if (multiLevelCategoryData?.productsData) return setPageType("category");
			if (multiLevelCategoryError) return setPageType("notfound");
			return;
		}

		if (categoryLoading || productLoading) return;

		if (singleCategoryData?.productsData) return setPageType("category");

		if (product) return setPageType("product");

		if (singleCategoryError && productError) return setPageType("notfound");
	}, [
		searchQuery,
		slug,
		slugPath,
		isMultiLevel,
		categoryLoading,
		productLoading,
		multiLevelCategoryData,
		multiLevelCategoryError,
		singleCategoryData,
		singleCategoryError,
		product,
		productError,
	]);

	if (categoriesError || searchError) {
		return (
			<div className='container text-center py-5'>
				<h1>Eroare la încărcarea paginii</h1>
				<Link href='/' className='btn btn-primary'>
					Înapoi
				</Link>
			</div>
		);
	}

	if (!pageType) return <LoadingSkeleton />;

	if (pageType === "homepage") {
		if (!categories) return <LoadingSkeleton />;

		return (
			<>
				<Hero />
				<Suspense fallback={<LoadingSkeleton />}>
					{
						categories
							.filter((cat) => cat?.products?.length > 0)
							.map((cat) => <CategoryProducts key={cat.slug} category={cat} />)}
				</Suspense>
				<div className='mt-5'></div>
				<Features />
			</>
		);
	}

	// ----- PRODUS -----
	if (pageType === "product") {
		if (!product) return <LoadingSkeleton />;

		return (
			<>
                    <div style={{ marginTop: 20 }}></div>
				<Suspense fallback={<LoadingSkeleton />}>
					<DynamicDetailsPopup product={product} randomUsers={Math.floor(Math.random() * 20) + 1} />
					<DynamicShopDetailsTab product={product} />
				</Suspense>
			</>
		);
	}

	// ----- CATEGORIE -----
	const activeCategoryData = isMultiLevel ? multiLevelCategoryData : singleCategoryData;

	if (pageType === "category") {
		if (!activeCategoryData?.productsData) return <LoadingSkeleton />;

		return (
			<>
				<div className='tf-page-title'>
					<div className='container-full'>
						<div className='heading text-center'>
							{activeCategoryData.categoryName}
							{activeCategoryData.subcategoryName && ` > ${activeCategoryData.subcategoryName}`}
							{activeCategoryData.thirdCategoryName &&
								` > ${activeCategoryData.thirdCategoryName}`}
						</div>
						{activeCategoryData.categoryDesc && (
							<p className='text-center text-2 text_black-2 mt_5'>
								{activeCategoryData.categoryDesc}
							</p>
						)}
					</div>
				</div>
				<Suspense fallback={<LoadingSkeleton />}>
					<DynamicShopFullwidth productsData={activeCategoryData.productsData} />
				</Suspense>
			</>
		);
	}

	// ----- SEARCH -----
	if (pageType === "search") {
		if (!searchResults) return <LoadingSkeleton />;

		const categoryContext = slug ? (Array.isArray(slug) ? slug : [slug]) : [];

		return (
			<>
				<div className='tf-page-title'>
					<div className='container-full'>
						<div className='heading text-center'>
							Rezultate căutare: {searchResults.query}
							{categoryContext.length > 0 && (
								<span className='text-muted'> în {categoryContext.join(" > ")}</span>
							)}
						</div>
						<p className='text-center text-2 text_black-2 mt_5'>
							{searchResults.total} {searchResults.total === 1 ? "produs găsit" : "produse găsite"}
						</p>
					</div>
				</div>

				{searchResults.products && searchResults.products.length > 0 ? (
					<Suspense fallback={<LoadingSkeleton />}>
						<DynamicShopFullwidth productsData={searchResults.products} />
					</Suspense>
				) : (
					<div className='container text-center py-5'>
						<h3>Nu am găsit produse pentru {searchResults.query}</h3>
						<Link href='/' className='btn btn-primary mt-3'>
							Înapoi la homepage
						</Link>
					</div>
				)}
			</>
		);
	}

	// ----- NOT FOUND -----
	if (pageType === "notfound") {
		return (
			<div className='container text-center py-5'>
				<h1>La acest moment nu exista conținut / produse disponibil(e) pe aceasta pagina.</h1>
				<Link href='/' className='btn btn-primary'>
					Înapoi
				</Link>
			</div>
		);
	}

	// fallback sigur (nu afișa notfound “default”)
	return <LoadingSkeleton />;
}
