import { memo } from "react";
import type React from "react";

import { getDisplayName, getThumbnailProps, filterImageText } from "@ax/helpers";
import { Tag } from "@ax/components";
import type { IComponent } from "@ax/types";

import * as S from "./style";

const getThumbnailData = (component: string, theme: string) => {
	const optionText = filterImageText(component);
	if (!optionText) return false;
	return getThumbnailProps(optionText, false, theme);
};

const SideModalOption = (props: IProps) => {
	const { option, handleClick, theme } = props;
	const isComponentString = typeof option === "string";
	const optionComponent = isComponentString ? option : option.component;

	const isNavigationDefault = !isComponentString && ["header", "footer"].includes(option.type);

	const navigationThumbnail = isNavigationDefault &&
		option.thumbnail && { alt: option.title, src: option.thumbnail.url };

	const thumbnailProps = navigationThumbnail || getThumbnailData(optionComponent, theme);

	const label = isNavigationDefault ? option.title : getDisplayName(optionComponent);

	const setOption = () => {
		if (handleClick) {
			handleClick(option);
		}
	};

	const handleKeyDown = (e: React.KeyboardEvent) => {
		if (e.key === "Enter") {
			setOption();
		}
	};

	const defaultTag =
		!isComponentString && option.tag ? (
			<S.TagWrapper data-testid="side-modal-option-tag">
				<Tag text={option.tag} type="square" />
			</S.TagWrapper>
		) : null;

	return (
		<S.Item onClick={setOption} tabIndex={0} onKeyDown={handleKeyDown} role="button" data-testid="side-modal-option">
			<S.Thumbnail data-testid="side-modal-option-img" {...thumbnailProps} />
			{label}
			{defaultTag}
		</S.Item>
	);
};

interface IProps {
	option: string | IComponent;
	handleClick?: (option: string | IComponent) => void;
	children: string;
	theme: string;
}

export default memo(SideModalOption);
