import clsx from 'clsx';
import React from 'react';

import { ScrollableProps } from '../shared/scrollable-props';
import { ScrollableHandle } from '../shared/handle';
import { useGlobalOsStyles } from '../styles/global';
import { useOverlayScrollbars } from '../hooks/use-overlay-scrollbars';

export const Scrollable = React.forwardRef<ScrollableHandle, ScrollableProps>(function Scrollable(
	props,
	ref
) {
	const { internals, children, className, options, extensions, ...rest } = props || {};

	const os = useOverlayScrollbars(ref, { options, extensions });
	useGlobalOsStyles();

	const internalProps = internals || {};
	const resizeObserverHostProps = internalProps.resizeObserverHost || {};
	const paddingProps = internalProps.padding || {};
	const viewPortProps = internalProps.viewPort || {};
	const contentProps = internalProps.content || {};
	const horizontalScrollbarProps = internalProps.horizontalScrollbar || {};
	const horizontalScrollbarTrackProps = internalProps.horizontalScrollbarTrack || {};
	const horizontalScrollbarHandleProps = internalProps.horizontalScrollbarHandle || {};
	const verticalScrollbarProps = internalProps.verticalScrollbar || {};
	const verticalScrollbarTrackProps = internalProps.verticalScrollbarTrack || {};
	const verticalScrollbarHandleProps = internalProps.verticalScrollbarHandle || {};
	const cornerProps = internalProps.corner || {};

	return (
		<div {...rest} ref={os.target} className={clsx('os-host', className)}>
			<div
				{...resizeObserverHostProps}
				className={clsx('os-resize-observer-host', resizeObserverHostProps.className)}
			/>
			<div {...paddingProps} className={clsx('os-padding', paddingProps.className)}>
				<div {...viewPortProps} className={clsx('os-viewport', viewPortProps.className)}>
					<div {...contentProps} className={clsx('os-content', contentProps.className)}>
						{children}
					</div>
				</div>
			</div>
			<div
				{...horizontalScrollbarProps}
				className={clsx(
					'os-scrollbar',
					'os-scrollbar-horizontal',
					horizontalScrollbarProps.className
				)}>
				<div
					{...horizontalScrollbarTrackProps}
					className={clsx('os-scrollbar-track', horizontalScrollbarTrackProps.className)}>
					<div
						{...horizontalScrollbarHandleProps}
						className={clsx(
							'os-scrollbar-handle',
							horizontalScrollbarHandleProps.className
						)}
					/>
				</div>
			</div>
			<div
				{...verticalScrollbarProps}
				className={clsx(
					'os-scrollbar',
					'os-scrollbar-vertical',
					verticalScrollbarProps.className
				)}>
				<div
					{...verticalScrollbarTrackProps}
					className={clsx('os-scrollbar-track', verticalScrollbarTrackProps.className)}>
					<div
						{...verticalScrollbarHandleProps}
						className={clsx(
							'os-scrollbar-handle',
							verticalScrollbarHandleProps.className
						)}
					/>
				</div>
			</div>
			<div {...cornerProps} className={clsx('os-scrollbar-corner', cornerProps.className)} />
		</div>
	);
});
