'use client'

import { useTranslations } from 'next-intl'
import { usePathname } from 'next/navigation'
import { Fragment } from 'react'

import { TbSeparator } from 'react-icons/tb'

import { Logo, Separator, Sheet, Typography } from '@/components/atoms'

import {
	contentStyles,
	footerStyles,
	groupHeadStyles,
	headerStyles,
	rootStyles,
	wrapperStyles
} from './Sidebar.styles'

import { Item } from './Item'
import { getSidebarGroups } from './Sidebar.utils'
import { Trigger } from './Trigger'
import { useSidebar } from '@/hooks'

const { Text } = Typography

function SidebarRoot({
	className,
	children,
	...props
}: React.ComponentProps<'div'>) {
	const { isMobile, isOpen, setIsOpen } = useSidebar()

	if (isMobile) {
		return (
			<Sheet
				open={isOpen}
				onOpenChange={setIsOpen}
				className='w-60 p-0'
				{...props}
			>
				<div className={wrapperStyles}>{children}</div>
			</Sheet>
		)
	}

	return (
		<div
			className='group peer'
			data-state={isOpen ? 'expanded' : 'collapsed'}
		>
			<div className={rootStyles()} />
			<div className={rootStyles({ content: true })} {...props}>
				<div className={wrapperStyles}>{children}</div>
			</div>
		</div>
	)
}

function Sidebar() {
	const t = useTranslations('')
	//
	const pathname = usePathname()
	//
	const groups = getSidebarGroups()

	return (
		<SidebarRoot>
			<div className={headerStyles}>
				<Logo />
				<Trigger />
			</div>
			<div className={contentStyles}>
				{groups.map(group => {
					return (
						<Fragment key={group.key}>
							<div className={groupHeadStyles}>
								<TbSeparator />
								{group.title ? (
									<Text size={'xs'} muted>
										{group.title}
									</Text>
								) : (
									<Separator className='w-full' />
								)}
							</div>
							<ul>
								{group.items.map(item => {
									const isActive =
										pathname.startsWith(item.url) ||
										pathname === item.url

									return (
										<Item
											key={item.title}
											href={item.url}
											tooltip={item.title}
											active={isActive}
										>
											<item.icon />
											<span>{item.title}</span>
										</Item>
									)
								})}
							</ul>
						</Fragment>
					)
				})}
			</div>
			<div className={footerStyles}>
				<Text size={'xs'}>
					<span>{t('version')}</span>{' '}
					{process.env.NEXT_PUBLIC_APP_VERSION}
				</Text>
			</div>
		</SidebarRoot>
	)
}

Sidebar.Trigger = Trigger

export { Sidebar }
