'use client';

import { cn } from '@/lib/utils';
import SidebarArrow from '@/shared/icons/sidebar/sidebar-arrow.svg';
import { removeLeadingSlash } from '@/utils/remove-leading-slash';
import { usePathname } from 'next/navigation';
import { sidebarPageIcon, TSidebarData } from './data';
import Link from 'next/link';

type TSidebarListProps = {
	openSidebar: boolean;
	sidebarItem: TSidebarData;
	activeItem: string | null;
	onItemClick: (name: string) => void;
};

const SidebarList = ({ openSidebar, sidebarItem, activeItem, onItemClick }: TSidebarListProps) => {
	const route = usePathname();
	const { name, href, subList } = sidebarItem;

	const fullHref = `/dashboard${href}`;
	
	// If the main item has sub-items, redirect to the first sub-item
	const redirectHref = subList.length > 0 ? `${fullHref}${subList[0].href}` : fullHref;

	// Check if current route starts with the item's href
	const isItemActive = route.startsWith(fullHref);

	// Check if any subItem is active
	const isSubItemActive = subList.some((sub) => route === `${fullHref}${sub.href}`);

	const isActive = activeItem === name || isItemActive || isSubItemActive;

	return (
		<div
			className={cn('py-3 px-4 w-full rounded-xl', {
				'w-fit': !openSidebar,
				'bg-[#F7F7FC]': isActive,
			})}>
			<div className='flex items-center justify-between cursor-pointer' onClick={() => onItemClick(name)}>
				<Link href={redirectHref} className='flex items-center gap-3'>
					<span
						className={cn('text-[#6E6E6E]', {
							'text-main-color': isActive,
						})}>
						{sidebarPageIcon[removeLeadingSlash(href)].icon}
					</span>
					{openSidebar ? (
						<span
							className={cn('font-medium text-[14px] leading-[140%] align-middle text-[#6E6E6E] capitalize', {
								'font-semibold text-[14px] leading-[100%] align-middle text-[#4F46E5]': isActive,
							})}>
							{name}
						</span>
					) : null}
				</Link>
				{openSidebar ? (
					<SidebarArrow
						className={cn('rotate-0 transition-transform duration-300', {
							'rotate-180': isActive,
						})}
					/>
				) : null}
			</div>

			{openSidebar && isActive && subList.length > 0 && (
				<div className='flex flex-col gap-2 mt-3'>
					{subList.map(({ name, href: subHref }) => {
						const fullSubHref = `${fullHref}${subHref}`;
						const isCurrentSubItemActive = route === fullSubHref;

						return (
							<Link
								key={name}
								href={fullSubHref}
								className={cn('pl-8 text-[14px] leading-[140%] align-middle text-[#2D3091] capitalize', {
									'text-main-color': isCurrentSubItemActive,
								})}>
								{name}
							</Link>
						);
					})}
				</div>
			)}
		</div>
	);
};

export default SidebarList;
