import type React from "react";
import { useState } from "react";
import { connect } from "react-redux";

import { RestoreModal } from "@ax/components";
import { activityLogActions } from "@ax/containers/ActivityLog";
import { navigationActions } from "@ax/containers/Navigation";
import { pageEditorActions } from "@ax/containers/PageEditor";
import { structuredDataActions } from "@ax/containers/StructuredData";
import { useModal } from "@ax/hooks";
import type { IRootState } from "@ax/types";

import type { LogActivityDTO, LogContentDTO, LogContentTypeDTO } from "@griddo/api-types";

import { eventKey } from "./../../../constants";
import DetailModal from "./../../../DetailModal";
import { getContentTypeSchemaVersion, getPageSchemaVersion } from "./../../../utils";

import * as S from "./style";

const EventItem = (props: IEventItemProps) => {
	const { item, schemaVersion, restorePage, restoreNavigation, restoreStructuredData, goToLogContent, getLog } = props;

	const { created, site, contentType, content, eventType } = item;

	const { isOpen: isDetailOpen, toggleModal: toggleDetailModal } = useModal();
	const { isOpen: isRestoreOpen, toggleModal: toggleRestoreModal } = useModal();
	const [schemaChange, setSchemaChange] = useState(false);

	const isDeleteEvent = eventType?.internal_key ? eventType.internal_key.includes("DELETED") : false;

	const restoreByContent = async (type: string, id: number) => {
		switch (type) {
			case eventKey.DELETED_PAGE:
			case eventKey.DELETED_CONTENT_TYPE_PAGE:
				return await restorePage(id);
			case eventKey.DELETED_HEADER:
				return await restoreNavigation(id, "header");
			case eventKey.DELETED_FOOTER:
				return await restoreNavigation(id, "footer");
			case eventKey.DELETED_CATEGORY:
			case eventKey.DELETED_CONTENT_TYPE:
				return await restoreStructuredData(id);
			default:
				return false;
		}
	};

	const handleRestore = async () => {
		const contentID = contentType?.id || content?.id;
		if (contentID && eventType?.internal_key) {
			const isRestored = await restoreByContent(eventType.internal_key, contentID);
			if (isRestored) {
				getLog();
				isRestoreOpen && toggleRestoreModal();
				isDetailOpen && toggleDetailModal();
			}
		}
	};

	const handleDetailRestorePage = async () => {
		const contentID = contentType?.id || content?.id || null;
		const hasSchemaVersion = [
			eventKey.DELETED_PAGE,
			eventKey.DELETED_CONTENT_TYPE_PAGE,
			eventKey.DELETED_CONTENT_TYPE,
		].includes(eventType?.internal_key || "");

		if (contentID && hasSchemaVersion) {
			const pageSchemaVersion =
				eventType?.internal_key === eventKey.DELETED_CONTENT_TYPE
					? await getContentTypeSchemaVersion(contentID)
					: await getPageSchemaVersion(contentID);
			if (schemaVersion !== pageSchemaVersion) {
				setSchemaChange(true);
			} else {
				setSchemaChange(false);
			}
		}

		toggleRestoreModal();
	};

	const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
		e.stopPropagation();
		const siteID = site?.id || null;
		goToLogContent(contentType, content, siteID);
	};

	const handleKeyDown = () => {
		const siteID = site?.id || null;
		goToLogContent(contentType, content, siteID);
	};

	return (
		<>
			<S.ActivityItem onClick={toggleDetailModal}>
				<S.EventWrapper>
					<S.Time>{created.hour}</S.Time>
					<S.Event>
						{eventType?.name || ""}{" "}
						<span
							onClick={!isDeleteEvent ? handleClick : undefined}
							role="button"
							tabIndex={0}
							onKeyDown={!isDeleteEvent ? handleKeyDown : undefined}
						>
							{content?.title || contentType?.title || ""}
						</span>
					</S.Event>
				</S.EventWrapper>
				<S.Site>
					<S.Label>Site</S.Label>
					<S.StyledTag
						text={site ? site.name : "Global"}
						type="square"
						color={site ? undefined : "#C3F4FF"}
						textColor="rgba(32, 34, 76, 0.6)"
						maxChar={30}
					/>
				</S.Site>
				<S.ContentType>
					{!!contentType && (
						<>
							<S.Label>Content type</S.Label>
							<S.StyledTag text={contentType.content?.title || ""} color="#E6E7F8" small={true} />
						</>
					)}
				</S.ContentType>
			</S.ActivityItem>
			<DetailModal
				isOpen={isDetailOpen}
				toggleModal={toggleDetailModal}
				itemLog={item}
				restorePage={handleDetailRestorePage}
				onClick={handleClick}
				onKeyDown={handleKeyDown}
			/>
			{isRestoreOpen && (
				<RestoreModal
					isOpen={isRestoreOpen}
					toggleModal={toggleRestoreModal}
					isChild={true}
					restorePage={handleRestore}
					hasIssues={schemaChange}
				/>
			)}
		</>
	);
};

interface IEventItemProps {
	item: LogActivityDTO;
	schemaVersion: string;
	restorePage(id: number): Promise<boolean>;
	restoreNavigation(navID: number, type: string): Promise<boolean>;
	restoreStructuredData(dataID: number): Promise<boolean>;
	goToLogContent(contentType: LogContentTypeDTO | null, content: LogContentDTO | null, site: number | null): void;
	getLog(): void;
}

const mapStateToProps = (state: IRootState) => ({
	schemaVersion: state.structuredData.schemaVersion,
});

const mapDispatchToProps = {
	restorePage: pageEditorActions.restorePage,
	restoreNavigation: navigationActions.restoreNavigation,
	restoreStructuredData: structuredDataActions.restoreStructuredDataContent,
	goToLogContent: activityLogActions.goToLogContent,
};

export default connect(mapStateToProps, mapDispatchToProps)(EventItem);
