import type { JSX } from "react"

import { X } from "lucide-react"
import { FunctionComponent } from "react"
import Drawer from "react-modern-drawer"

import cs from "classnames"
import Link from "next/link"
import { usePathname } from "next/navigation"

import { INavigationDrawerProps } from "./NavigationDrawer.d"
import styles from "./NavigationDrawer.module.scss"

import "react-modern-drawer/dist/index.css"

export const NavigationDrawer: FunctionComponent<INavigationDrawerProps> = ({
	buttons,
	className,
	open,
	onClose,
	position = "left",
	size = 280,
	title,
}): JSX.Element => {
	const pathname = usePathname()

	return (
		<Drawer
			open={open}
			onClose={onClose}
			direction={position}
			size={size}
			className={cs(styles.drawer, className)}
			aria-label="Навигация"
			duration={200}
		>
			<nav className={styles.root} data-testid="NavigationDrawer">
				<div className={styles.header}>
					<span className={styles.brand}>{title ?? "Coffee Project"}</span>
					<button
						type="button"
						className={styles.closeButton}
						onClick={onClose}
						aria-label="Закрыть навигацию"
					>
						<X />
					</button>
				</div>
				<ul className={styles.list}>
					{buttons.map(({ label, icon: Icon, path, action }, index) => {
						const key = `${label}-${path ?? index}`
						const isActive = path ? pathname === path : false

						const content = (
							<>
								{Icon ? <Icon className={styles.icon} /> : null}
								<span className={styles.label}>{label}</span>
							</>
						)

						const handleClick = (): void => {
							action?.()
							onClose()
						}

						return (
							<li className={styles.item} key={key}>
								{path ? (
									<Link
										href={path}
										className={cs(styles.link, isActive && styles.active)}
										onClick={handleClick}
									>
										{content}
									</Link>
								) : (
									<button
										type="button"
										className={styles.button}
										onClick={handleClick}
									>
										{content}
									</button>
								)}
							</li>
						)
					})}
				</ul>
			</nav>
		</Drawer>
	)
}
