import { useMemo, useState } from "react";

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

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

import * as S from "./style";

const ErrorsBanner = (props: IErrorsBannerProps) => {
	const { errors, onSelectHeading, isOpen, setIsOpen, resetKey } = props;

	const [isDeleted, setIsDeleted] = useState(false);
	const [deletedErrorIndices, setDeletedErrorIndices] = useState<Set<number>>(new Set());
	const [isSticky, setIsSticky] = useState(false);

	const allErrorsDeleted = useMemo(
		() => deletedErrorIndices.size === errors.length && errors.length > 0,
		[deletedErrorIndices.size, errors.length],
	);

	const handleErrorDelete = (index: number) => {
		setDeletedErrorIndices((prev) => new Set([...prev, index]));
	};

	const handleNavigateHeading = () => {
		setIsSticky(true);
	};

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

	return (
		<S.ErrorsWrapper isSticky={isSticky}>
			<S.ErrorsHeader>
				<S.WarningWrapper>
					<Icon name="warning" size="16" />
				</S.WarningWrapper>
				<S.HeaderText>SEO Alerts</S.HeaderText>
				<S.HeaderActions>
					<S.ToggleWrapper
						onClick={() => {
							setIsOpen(!isOpen);
							setIsSticky(false);
						}}
					>
						<Icon name={isOpen ? "UpArrow" : "DownArrow"} size="24" />
					</S.ToggleWrapper>
					<S.IconWrapper
						onClick={() => {
							setIsDeleted(true);
							setIsSticky(false);
							setIsOpen(false);
						}}
					>
						<Icon name="close" size="16" />
					</S.IconWrapper>
				</S.HeaderActions>
			</S.ErrorsHeader>
			<S.ErrorsContent isOpen={isOpen}>
				<S.Description>
					Review <strong>suggestions and warnings</strong> to enhance your page's search engine optimization.
				</S.Description>
				<S.ErrorListWrapper>
					{errors.map((error, index) => (
						<ErrorItem
							key={`${error.message}-${resetKey}`}
							error={error}
							onSelectHeading={onSelectHeading}
							onDelete={() => handleErrorDelete(index)}
							onNavigateHeading={handleNavigateHeading}
							parentIsOpen={isOpen}
						/>
					))}
				</S.ErrorListWrapper>
			</S.ErrorsContent>
		</S.ErrorsWrapper>
	);
};

interface IErrorsBannerProps {
	errors: IHeadingError[];
	onSelectHeading: (id: number) => () => void;
	isOpen: boolean;
	setIsOpen: (value: boolean) => void;
	resetKey: number;
}

export default ErrorsBanner;
