"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { fetchWrapper } from "@/helpers";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination, Autoplay } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";

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

export default function Hero() {
	const [categories, setCategories] = useState([]);
	const [activeCategory, setActiveCategory] = useState(null);
	const [hovering, setHovering] = useState(false);
	const [categoryChildren, setCategoryChildren] = useState({});
	const [loadingChildren, setLoadingChildren] = useState(false);

     const { t } = useT(); 

     const getCategoryVariable = (category) => {
          if(t("variable_categorii") === 'name') {
               return category.name; 
          }

          if(t("variable_categorii") === 'name_en') {
               return category.name_en; 
          }

          if(t("variable_categorii") === 'name_it') {
               return category.name_it; 
          }

          if(t("variable_categorii") === 'name_fr') {       
               return category.name_fr;
          }
          if(t("variable_categorii") === 'name_de') {
               return category.name_de;
          }    

          return category.name; 
     };

	useEffect(() => {
		async function fetchCategories() {
			const response = await fetchWrapper.get(`/api/categories/main`);
			setCategories(response.categories);
		}
		fetchCategories();
	}, []);

	const handleCategoryHover = async (category) => {
		setActiveCategory(category);
		
		if (categoryChildren[category.id]) {
			return;
		}

		setLoadingChildren(true);
		try {
			const response = await fetchWrapper.get(`/api/categories/${category.id}/children`);
			setCategoryChildren(prev => ({
				...prev,
				[category.id]: response.children
			}));
		} catch (error) {
			console.error("Error fetching category children:", error);
		} finally {
			setLoadingChildren(false);
		}
	};

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

	return (
		<section className='container'>
			<div
				className='row g-0 d-none d-lg-flex'
				onMouseEnter={() => setHovering(true)}
				onMouseLeave={() => {
					setHovering(false);
					setActiveCategory(null);
				}}
				style={{ minHeight: "400px" }}>
				{/* Left sidebar - main categories */}
				<div className='col-lg-3 bg-white border border-end-0 rounded-start shadow-sm p-0'>
					<ul className='list-group list-group-flush'>
						{categories.map((category) => {
							const productCount = formatProductCount(category.productCount);
							
							return (
								<li
									key={category.id}
									className='list-group-item list-group-item-action'
									onMouseEnter={() => handleCategoryHover(category)}
									style={{ cursor: "pointer" }}>
									<div className='d-flex justify-content-between align-items-center'>
										<div className="d-flex align-items-center gap-2">
											<span>{getCategoryVariable(category)}</span>
											{productCount && (
												<span
													style={{
														backgroundColor: "#f0f0f0",
														color: "#666",
														fontSize: "11px",
														padding: "2px 8px",
														borderRadius: "12px",
														fontWeight: "500",
														minWidth: "32px",
														textAlign: "center"
													}}>
													{productCount}
												</span>
											)}
										</div>
										<span>›</span>
									</div>
								</li>
							);
						})}
					</ul>
				</div>

				{/* Right content area */}
				<div className='col-lg-9 position-relative p-0'>
					{/* Categories panel */}
					<div
						className={`subcat-panel bg-white border-start-0 rounded-end shadow-sm ${
							hovering && activeCategory ? "active" : ""
						}`}
						style={{
							position: "absolute",
							top: 0,
							left: 0,
							right: 0,
							bottom: 0,
							zIndex: 10,
							overflowY: "auto",
							padding: "1.5rem",
							display: hovering && activeCategory ? "block" : "none",
						}}>
						{activeCategory && (
							<>
								<h5 className='mb-3'>
									{t("subcategories_heading")}<strong>{getCategoryVariable(activeCategory)}</strong>
								</h5>
								
								{loadingChildren ? (
									<div className='text-center py-4'>
										<div className="spinner-border text-primary" role="status">
											<span className="visually-hidden">Loading...</span>
										</div>
									</div>
								) : categoryChildren[activeCategory.id] ? (
									<div className='row'>
										{categoryChildren[activeCategory.id].map((subCategory) => {
											const subCategoryCount = formatProductCount(subCategory.productCount);
											
											return (
												<div className='col-md-4 mb-4' key={subCategory.id}>
													<Link
														href={`/${activeCategory.slug}/${subCategory.slug}`}
														className='text-decoration-none text-dark fw-bold d-flex align-items-center gap-2 mb-2'
														style={{ fontSize: "14px" }}>
														<span>{getCategoryVariable(subCategory)}</span>
														{subCategoryCount && (
															<span
																style={{
																	backgroundColor: "#e3f2fd",
																	color: "#1976d2",
																	fontSize: "11px",
																	padding: "2px 7px",
																	borderRadius: "10px",
																	fontWeight: "600",
																	minWidth: "28px",
																	textAlign: "center"
																}}>
																{subCategoryCount}
															</span>
														)}
													</Link>
													<div className='d-flex flex-column'>
														{subCategory.subChildren?.map((subChild) => {
															const subChildCount = formatProductCount(subChild.productCount);
															
															return (
																<Link
																	key={subChild.id}
																	href={`/${activeCategory.slug}/${subCategory.slug}/${subChild.slug}`}
																	className='text-decoration-none text-muted mb-1 d-flex align-items-center gap-2'
																	style={{ 
																		fontSize: "13px",
																		transition: "color 0.2s"
																	}}
																	onMouseEnter={(e) => {
																		e.currentTarget.style.color = "#1976d2";
																	}}
																	onMouseLeave={(e) => {
																		e.currentTarget.style.color = "#6c757d";
																	}}>
																	<span>{getCategoryVariable(subChild)}</span>
																	{subChildCount && (
																		<span
																			style={{
																				backgroundColor: "#f5f5f5",
																				color: "#757575",
																				fontSize: "10px",
																				padding: "1px 6px",
																				borderRadius: "8px",
																				fontWeight: "500",
																				minWidth: "24px",
																				textAlign: "center"
																			}}>
																			{subChildCount}
																		</span>
																	)}
																</Link>
															);
														})}
													</div>
												</div>
											);
										})}
									</div>
								) : (
									<div className='text-center py-4 text-muted'>
										Nu s-au găsit subcategorii
									</div>
								)}
							</>
						)}
					</div>

					{/* Slider (shown when no category is hovered) */}
					{!activeCategory && (
						<Swiper
							modules={[Pagination, Autoplay]}
							pagination={{ clickable: true }}
							autoplay={{ delay: 3000 }}
							loop={true}
							spaceBetween={0}
							slidesPerView={1}
							style={{ height: "100%" }}>
							{[
								"https://emagyl.s3.eu-north-1.amazonaws.com/emagyl_banner.webp",
							].map((src, idx) => (
								<SwiperSlide key={idx}>
									<img
										src={src}
										alt={`Promo ${idx + 1}`}
										className='w-100 h-100'
										style={{
											objectFit: "cover",
											minHeight: "400px",
										}}
									/>
								</SwiperSlide>
							))}
						</Swiper>
					)}
				</div>
			</div>
		</section>
	);
}