"use client";
import React, { useState, useEffect } from "react";
import Link from "next/link";

import { useT } from "@/context/I18nContext"; 

export default function MobileMenu() {
	const [navigationStack, setNavigationStack] = useState([]);
	const [loading, setLoading] = useState(true);
	const [childrenCache, setChildrenCache] = useState({});
	const [expandedCategories, setExpandedCategories] = useState(new Set());

     const { t } = useT(); 

	useEffect(() => {
		fetchMainCategories();
	}, []);

	const fetchMainCategories = async () => {
		try {
			setLoading(true);
			const response = await fetch("/api/categories/main");
			const data = await response.json();
			setNavigationStack([
				{
					categories: data.categories || [],
					title: "Contul meu",
					level: 0,
					breadcrumb: [],
				},
			]);
		} catch (error) {
			console.error("Error fetching main categories:", error);
		} finally {
			setLoading(false);
		}
	};

	const fetchChildren = async (categoryId) => {
		if (childrenCache[categoryId]) {
			return childrenCache[categoryId];
		}

		try {
			const response = await fetch(`/api/categories/${categoryId}/children`);
			const data = await response.json();
			const children = data.children || [];

			setChildrenCache((prev) => ({ ...prev, [categoryId]: children }));
			return children;
		} catch (error) {
			console.error("Error fetching children:", error);
			return [];
		}
	};

	const toggleDropdown = (categoryId) => {
		setExpandedCategories((prev) => {
			const newSet = new Set(prev);
			if (newSet.has(categoryId)) {
				newSet.delete(categoryId);
			} else {
				newSet.add(categoryId);
			}
			return newSet;
		});
	};

	const buildCategoryUrl = (breadcrumb, currentSlug) => {
		const slugs = [...breadcrumb.map((b) => b.slug), currentSlug];
		return `/${slugs.join("/")}`;
	};

	const formatProductCount = (count) => {
		if (!count || count === 0) return null;
		if (count >= 1000) {
			return `${(count / 1000).toFixed(1)}k`.replace(".0k", "k");
		}
		return count.toString();
	};

	const handleCategoryClick = async (category, e) => {
		e.preventDefault();
		e.stopPropagation();

		const currentBreadcrumb = navigationStack[navigationStack.length - 1].breadcrumb || [];
		const children = await fetchChildren(category.id);

		if (children.length > 0) {
			const currentLevel = navigationStack.length - 1;
			setNavigationStack((prev) => [
				...prev,
				{
					categories: children,
					title: category.name,
					parentCategory: category,
					level: currentLevel + 1,
					breadcrumb: [...currentBreadcrumb, { slug: category.slug, name: category.name }],
				},
			]);
			setExpandedCategories(new Set());
		} else {
			const url = buildCategoryUrl(currentBreadcrumb, category.slug);
			window.location.href = url;
		}
	};

	const handleSubChildClick = (subChild, e) => {
		e.preventDefault();
		e.stopPropagation();

		const currentBreadcrumb = navigationStack[navigationStack.length - 1].breadcrumb || [];
		const url = buildCategoryUrl(currentBreadcrumb, subChild.slug);
		window.location.href = url;
	};

	const handleBack = () => {
		setNavigationStack((prev) => prev.slice(0, -1));
		setExpandedCategories(new Set());
	};

	const currentView = navigationStack[navigationStack.length - 1] || {
		categories: [],
		title: "Meniu",
		breadcrumb: [],
	};
	const showBackButton = navigationStack.length > 1;

	return (
		<div className='offcanvas offcanvas-start canvas-mb' id='mobileMenu'>
			<span className='icon-close icon-close-popup' data-bs-dismiss='offcanvas' aria-label='Close' />
			<div className='mb-canvas-content'>
				<div className='mb-body'>
					{/* Header */}
					<div
						className='mb-menu-header'
						style={{
							padding: "16px 16px",
							borderBottom: "1px solid #e5e5e5",
							display: "flex",
							alignItems: "center",
							gap: "12px",
							backgroundColor: "#fff",
							position: "sticky",
							top: 0,
							zIndex: 10,
						}}>
						{showBackButton && (
							<button
								onClick={handleBack}
								className='btn-back'
								style={{
									background: "none",
									border: "none",
									padding: "4px",
									cursor: "pointer",
									display: "flex",
									alignItems: "center",
									fontSize: "20px",
									color: "#333",
								}}
								aria-label='Înapoi'>
								←
							</button>
						)}
					</div>

					{/* Lista categorii */}
					{loading ? (
						<div style={{ padding: "40px 20px", textAlign: "center", color: "#666" }}>
							Se încarcă categoriile...
						</div>
					) : (
						<ul
							className='nav-ul-mb'
							style={{
								padding: "0",
								margin: "0",
								listStyle: "none",
							}}>
							<li
								key='all-products'
								className='nav-mb-item'
								style={{
									borderBottom: "1px solid #f0f0f0",
								}}>
								<div
									onClick={() => window.location.href="/toate-produsele"}
									className='category-item'
									style={{
										padding: "14px 16px",
										display: "flex",
										alignItems: "center",
										justifyContent: "space-between",
										cursor: "pointer",
										transition: "background-color 0.15s ease",
										backgroundColor: "transparent",
										flex: 1,
									}}
									onMouseDown={(e) => {
										e.currentTarget.style.backgroundColor = "#f5f5f5";
									}}
									onMouseUp={(e) => {
										e.currentTarget.style.backgroundColor = "transparent";
									}}
									onMouseLeave={(e) => {
										e.currentTarget.style.backgroundColor = "transparent";
									}}>
									<div
										style={{
											display: "flex",
											alignItems: "center",
											flex: 1,
											gap: "12px",
										}}>
										<span
											style={{
												fontSize: "14px",
												color: "#262626",
												fontWeight: "400",
											}}>
											{t("magazin")}
										</span>
									</div>
								</div>
							</li>
                                   							<li
								key='all-products'
								className='nav-mb-item'
								style={{
									borderBottom: "1px solid #f0f0f0",
								}}>
								<div
									onClick={() => window.location.href="/reduceri"}
									className='category-item'
									style={{
										padding: "14px 16px",
										display: "flex",
										alignItems: "center",
										justifyContent: "space-between",
										cursor: "pointer",
										transition: "background-color 0.15s ease",
										backgroundColor: "transparent",
										flex: 1,
									}}
									onMouseDown={(e) => {
										e.currentTarget.style.backgroundColor = "#f5f5f5";
									}}
									onMouseUp={(e) => {
										e.currentTarget.style.backgroundColor = "transparent";
									}}
									onMouseLeave={(e) => {
										e.currentTarget.style.backgroundColor = "transparent";
									}}>
									<div
										style={{
											display: "flex",
											alignItems: "center",
											flex: 1,
											gap: "12px",
										}}>
										<span
											style={{
												fontSize: "14px",
												color: "red",
												fontWeight: "400",
											}}>
											{t("reduceri")}
										</span>
									</div>
								</div>
							</li>
							{currentView.categories.map((category) => {
								const hasSubChildren = category.subChildren && category.subChildren.length > 0;
								const isExpanded = expandedCategories.has(category.id);
								const productCount = formatProductCount(category.productCount);

								return (
									<li
										key={category.id}
										className='nav-mb-item'
										style={{
											borderBottom: "1px solid #f0f0f0",
										}}>
										{/* Main category item */}
										<div
											style={{
												display: "flex",
												alignItems: "center",
											}}>
											{/* Click pe toată categoria pentru navigare */}
											<div
												onClick={(e) => handleCategoryClick(category, e)}
												className='category-item'
												style={{
													padding: "14px 16px",
													display: "flex",
													alignItems: "center",
													justifyContent: "space-between",
													cursor: "pointer",
													transition: "background-color 0.15s ease",
													backgroundColor: "transparent",
													flex: 1,
												}}
												onMouseDown={(e) => {
													e.currentTarget.style.backgroundColor = "#f5f5f5";
												}}
												onMouseUp={(e) => {
													e.currentTarget.style.backgroundColor = "transparent";
												}}
												onMouseLeave={(e) => {
													e.currentTarget.style.backgroundColor = "transparent";
												}}>
												<div
													style={{
														display: "flex",
														alignItems: "center",
														flex: 1,
														gap: "12px",
													}}>
													<span
														style={{
															fontSize: "14px",
															color: "#262626",
															fontWeight: "400",
														}}>
														{category.name}
													</span>

													{/* Badge cu numărul de produse */}
													{productCount && (
														<span
															style={{
																backgroundColor: "#f0f0f0",
																color: "#666",
																fontSize: "12px",
																padding: "2px 8px",
																borderRadius: "12px",
																fontWeight: "500",
																minWidth: "32px",
																textAlign: "center",
															}}>
															{productCount}
														</span>
													)}
												</div>
											</div>

											{/* Buton separat pentru dropdown (doar dacă sunt subChildren pe nivel 2) */}
											{hasSubChildren && currentView.level === 1 && (
												<button
													onClick={(e) => handleCategoryClick(category, e)}
													style={{
														background: "none",
														border: "none",
														padding: "14px 16px",
														cursor: "pointer",
														display: "flex",
														alignItems: "center",
														color: "#999",
														fontSize: "16px",
													}}
													aria-label={isExpanded ? "Închide" : "Deschide"}>
													<i
														style={{
															transform: isExpanded
																? "rotate(180deg)"
																: "rotate(0deg)",
															transition: "transform 0.2s ease",
														}}>
														{">"}
													</i>
												</button>
											)}
										</div>
									</li>
								);
							})}
						</ul>
					)}

					{/* Link "Vezi toate produsele" */}
					{showBackButton && currentView.parentCategory && (
						<div
							style={{
								padding: "16px",
								borderTop: "2px solid #e5e5e5",
								backgroundColor: "#fafafa",
							}}>
							<Link
								href={buildCategoryUrl(
									currentView.breadcrumb.slice(0, -1),
									currentView.parentCategory.slug
								)}
								style={{
									display: "block",
									textAlign: "center",
									padding: "12px 16px",
									backgroundColor: "#0066cc",
									color: "#fff",
									textDecoration: "none",
									borderRadius: "4px",
									fontSize: "14px",
									fontWeight: "600",
									transition: "background-color 0.2s",
								}}
								onMouseEnter={(e) => {
									e.currentTarget.style.backgroundColor = "#0052a3";
								}}
								onMouseLeave={(e) => {
									e.currentTarget.style.backgroundColor = "#0066cc";
								}}>
								Vezi toate din {currentView.parentCategory.name}
							</Link>
						</div>
					)}

					<div style={{ height: "80px" }} />
				</div>

				{/* Footer fix */}
				<div
					className='mb-bottom'
					style={{
						padding: "16px",
						borderTop: "1px solid #e5e5e5",
						backgroundColor: "#fff",
						position: "sticky",
						bottom: 0,
					}}>
					<Link
						href={`/autentificare`}
						className='site-nav-icon'
						style={{
							display: "flex",
							alignItems: "center",
							gap: "8px",
							textDecoration: "none",
							color: "#333",
							fontSize: "14px",
						}}>
						<i className='icon icon-account' style={{ fontSize: "18px" }} />
						{t("autentificare")}
					</Link>
				</div>
			</div>
		</div>
	);
}
