import { useEffect, useRef } from "react";
import { getThumbnailProps, trimText } from "@ax/helpers";
import type { IStructuredData, ITemplateOption } from "@ax/types";
import { Icon } from "@ax/components";

import * as S from "./style";

const ContentItem = (props: IContentItemProps) => {
	const { item, theme, isSelected, structuredData, pack, listRef, onClick } = props;
	const { title, name, dataPacks } = item;
	const { fromPage } = structuredData || { fromPage: false };
	const isSimpleData = !fromPage;
	const itemRef = useRef<HTMLDivElement>(null);

	useEffect(() => {
		if (itemRef.current && isSelected) {
			itemRef.current.focus();
		}
	}, [isSelected]);

	const thumbnailProps = getThumbnailProps(name, true, theme);

	const handleKeyDown = () => {
		setTimeout(() => {
			const scrollContainer = listRef.current;
			const activeElement = document.activeElement as HTMLElement | null;

			if (!scrollContainer || !activeElement) return;
			if (!scrollContainer.contains(activeElement)) return;

			const item = activeElement;

			const itemRect = item.getBoundingClientRect();
			const containerRect = scrollContainer.getBoundingClientRect();

			const itemBottomInContainer = itemRect.bottom - containerRect.top + scrollContainer.scrollTop;
			const visibleBottom = scrollContainer.scrollTop + scrollContainer.clientHeight - 70;

			if (itemBottomInContainer > visibleBottom) {
				scrollContainer.scrollTo({
					top: scrollContainer.scrollTop + (itemBottomInContainer - visibleBottom),
				});
			}
		}, 0);
	};

	const TypeTag = () =>
		fromPage ? (
			<S.TypeTag>
				<Icon name="page" size="16" />
				Page
			</S.TypeTag>
		) : (
			<S.TypeTag>
				<Icon name="alignLeft" size="16" />
				Simple
			</S.TypeTag>
		);

	return (
		<S.Wrapper
			isSelected={isSelected}
			onClick={onClick}
			onFocus={onClick}
			onKeyDown={handleKeyDown}
			role="button"
			tabIndex={0}
			ref={itemRef}
			data-testid="card-item"
		>
			<S.Content>
				{(!isSimpleData || (isSimpleData && !!thumbnailProps)) && (
					<S.ThumbnailWrapper isSimple={isSimpleData}>
						{thumbnailProps ? (
							<S.Thumbnail backgroundUrl={thumbnailProps.src} />
						) : (
							<S.PlaceHolder>
								<Icon name="image" size="36" />
							</S.PlaceHolder>
						)}
					</S.ThumbnailWrapper>
				)}
				<S.DataWrapper>
					<S.NameWrapper>
						<S.Name>{trimText(title, 18)}</S.Name>
						{dataPacks && pack && <S.DataPack>{pack} datapack</S.DataPack>}
					</S.NameWrapper>
					<TypeTag />
				</S.DataWrapper>
			</S.Content>
		</S.Wrapper>
	);
};

interface IContentItemProps {
	item: ITemplateOption;
	theme: string;
	isSelected: boolean;
	structuredData?: IStructuredData;
	pack?: string;
	onClick: () => void;
	listRef: React.RefObject<HTMLDivElement>;
}

export default ContentItem;
