import { Icon } from "@ax/components";
import { getFormattedDateWithTimezone, getSlugFromUrl } from "@ax/helpers";
import type { IDataSource, IStructuredDataContent } from "@ax/types";

import { useSortable } from "@dnd-kit/sortable";

import * as S from "./style";

const Item = (props: IProps) => {
	const { item, handleDelete, listLength, source, isDragging } = props;

	const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
		id: item.id,
	});

	const removeItem = () => {
		handleDelete(item);
	};

	const menuOptions = [
		{
			label: "delete",
			icon: "delete",
			action: removeItem,
		},
	];

	return (
		<S.Item
			ref={setNodeRef}
			cssTransform={transform}
			transition={transition}
			{...listeners}
			{...attributes}
			data-testid="reference-field-item"
			margin={listLength < 2}
			isDragging={isDragging}
		>
			<S.HandleWrapper hidden={listLength < 2} data-testid="handle-wrapper">
				<S.IconHandleWrapper>
					<Icon name="drag" size="16" />
				</S.IconHandleWrapper>
			</S.HandleWrapper>
			<S.TextWrapper>
				<S.Header>
					<S.Type>{source?.title.toUpperCase()}</S.Type>
					{item.modified && <S.Date>{getFormattedDateWithTimezone(item.modified, "d MMM yy")}</S.Date>}
					<S.StyledActionMenu icon="more" options={menuOptions} size="s" tooltip="Actions" />
				</S.Header>
				<S.Title>{item.content.title}</S.Title>
				<S.Slug>{getSlugFromUrl(item.relatedPage?.url)}</S.Slug>
			</S.TextWrapper>
		</S.Item>
	);
};

interface IProps {
	item: IStructuredDataContent;
	listLength: number;
	source?: IDataSource;
	isDragging: boolean;
	handleDelete(item: IStructuredDataContent): void;
}

export default Item;
