import { useEffect, useState } from "react";

import { Icon, Tooltip } from "@ax/components";

import type { IHeadingError } from "../../utils";

import * as S from "./style";

const ErrorsItem = (props: IErrorsItemProps) => {
	const { error, onSelectHeading, onDelete, onNavigateHeading, parentIsOpen } = props;
	const { message, description, headingIds } = error;

	const [isOpen, setIsOpen] = useState(false);
	const [isDeleted, setIsDeleted] = useState(false);
	const [currentIndex, setCurrentIndex] = useState<number | null>(null);

	useEffect(() => {
		if (!parentIsOpen) {
			setIsOpen(false);
		}
	}, [parentIsOpen]);

	const handlePrevious = () => {
		if (!currentIndex) return;
		const newIndex = currentIndex - 1;
		setCurrentIndex(newIndex);
		onSelectHeading(headingIds[newIndex])();
	};

	const handleNext = () => {
		const newIndex = currentIndex === null ? 0 : currentIndex + 1;
		if (newIndex > headingIds.length - 1) return;
		setCurrentIndex(newIndex);
		onSelectHeading(headingIds[newIndex])();
	};

	const handleOpen = () => {
		setIsOpen(!isOpen);
		setCurrentIndex(0);
		onSelectHeading(headingIds[0])();
		!isOpen && onNavigateHeading();
	};

	const errorText =
		headingIds.length > 1 && currentIndex !== null
			? `${currentIndex + 1} of ${headingIds.length} headings`
			: `${headingIds.length} headings`;

	if (isDeleted) {
		return <></>;
	}

	return (
		<S.ErrorItem>
			<Tooltip content={description}>
				<S.ErrorHeader>
					<S.ErrorMessage>{message}</S.ErrorMessage>
					<S.ErrorActions>
						{headingIds.length > 0 && (
							<S.IconWrapper onClick={handleOpen}>
								<Icon name={isOpen ? "UpArrow" : "DownArrow"} size="16" />
							</S.IconWrapper>
						)}
						<S.IconWrapper
							onClick={() => {
								setIsDeleted(true);
								onDelete();
							}}
						>
							<Icon name="close" size="16" />
						</S.IconWrapper>
					</S.ErrorActions>
				</S.ErrorHeader>
			</Tooltip>
			<S.ErrorContentWrapper isOpen={isOpen}>
				<S.ErrorContent>
					<S.ErrorContentActions>
						<S.IconWrapper onClick={handlePrevious} isDisabled={!currentIndex}>
							<Icon name="UpArrow" size="16" />
						</S.IconWrapper>
						<S.IconWrapper onClick={handleNext} isDisabled={currentIndex === headingIds.length - 1}>
							<Icon name="DownArrow" size="16" />
						</S.IconWrapper>
					</S.ErrorContentActions>
					<S.ErrorContentText>{errorText}</S.ErrorContentText>
				</S.ErrorContent>
			</S.ErrorContentWrapper>
		</S.ErrorItem>
	);
};

interface IErrorsItemProps {
	error: IHeadingError;
	onSelectHeading: (id: number) => () => void;
	onDelete: () => void;
	onNavigateHeading: () => void;
	parentIsOpen: boolean;
}

export default ErrorsItem;
