import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import { appActions } from "@ax/containers/App";
import { pageEditorActions } from "@ax/containers/PageEditor";
import { sitesActions } from "@ax/containers/Sites";
import { structuredDataActions } from "@ax/containers/StructuredData";
import { usersActions } from "@ax/containers/Users";
import { ISetCurrentPageIDAction } from "@ax/containers/PageEditor/interfaces";
import { IImage, IRootState, ISite, IUser } from "@ax/types";
import { images } from "@ax/api";
import { isReqOk } from "@ax/helpers";
import { EmptyState, Loading } from "@ax/components";

import Item from "./Item";
import ItemGroup from "./ItemGroup";

import * as S from "./style";

const UsageContent = (props: IProps) => {
	const {
		image,
		currentSiteID,
		selectedTab,
		currentUser,
		setHistoryPush,
		setCurrentPageID,
		getSite,
		setCurrentDataID,
		setSelectedStructuredData,
		getUserCurrentPermissions,
		setCurrentSiteInfo,
		getDataContent,
	} = props;

	const { id } = image;

	const [items, setItems] = useState<IInUseItems>();
	const [loading, setLoading] = useState(false);

	const isSiteView = !!currentSiteID;

	useEffect(() => {
		const getInUseItems = async () => {
			const response = await images.getImageInUse(id);
			if (isReqOk(response?.status)) {
				return response.data;
			} else {
				console.log("Error en getInUseItems");
				return [];
			}
		};

		let isMounted = true;
		setLoading(true);
		if (isMounted) {
			getInUseItems().then((result: IInUseItems) => {
				setItems(result);
				setLoading(false);
			});
		}

		return function cleanup() {
			isMounted = false;
		};
	}, [id]);

	const getPageList = () => {
		if (!items) return <></>;
		if (isSiteView && selectedTab !== "global") {
			const pages = items.sites.find((site) => site.id === currentSiteID)?.pages || [];
			const data = items.sites.find((site) => site.id === currentSiteID)?.simpleContent || [];
			const pageItems = pages.map((item: IImageUseItem) => {
				const handleClick = () => {
					setCurrentPageID(item.id);
					setHistoryPush("/sites/pages/editor", true);
				};

				return <Item title={item.title} type="Page" date={item.date} key={item.id} onClick={handleClick} />;
			});

			const dataItems = data.map((item: IImageUseItem) => {
				const handleClick = async () => {
					if (!item.structuredData) return;
					setSelectedStructuredData(item.structuredData.id, "site");
					setCurrentDataID(item.id);
					await getDataContent(item.id);
					setHistoryPush(`/sites/data/${item.structuredData.id}/editor`);
				};

				return (
					<Item
						title={item.title}
						type={item.structuredData?.title || ""}
						date={item.date}
						key={item.id}
						onClick={handleClick}
					/>
				);
			});
			return [...pageItems, ...dataItems];
		} else {
			return items.sites.map((item) => {
				const hasSite = currentUser?.isSuperAdmin || !!currentUser?.roles.find((rol) => rol.siteId === item.id);
				const handleClick = async (page: IImageUseItem) => {
					await getSite(item.id);
					if (!page.structuredData) {
						setCurrentPageID(page.id);
						setHistoryPush("/sites/pages/editor", true);
					} else {
						setSelectedStructuredData(page.structuredData.id, "site");
						setCurrentDataID(page.id);
						await getDataContent(page.id);
						setHistoryPush(`/sites/data/${page.structuredData.id}/editor`);
					}
				};
				return (
					<ItemGroup
						key={item.id}
						title={item.title}
						items={[...item.pages, ...item.simpleContent]}
						onClick={handleClick}
						disabled={!hasSite}
					/>
				);
			});
		}
	};

	const getGlobalPageList = () => {
		if (!items || items.globalPages.length === 0) {
			return <></>;
		}
		const hasGlobal = currentUser?.isSuperAdmin || !!currentUser?.roles.find((rol) => rol.siteId === "global");
		const handleClick = (item: IImageUseItem) => {
			setCurrentPageID(item.id);
			if (isSiteView) {
				setCurrentSiteInfo(null);
				getUserCurrentPermissions();
			}
			const path = "/data/pages/editor";
			setHistoryPush(path, true);
		};
		return <ItemGroup title="Global Pages" items={items.globalPages} onClick={handleClick} disabled={!hasGlobal} />;
	};

	const getGlobalStructuredDataList = () => {
		if (!items || items.simpleData.length === 0) {
			return <></>;
		}
		const hasGlobal = currentUser?.isSuperAdmin || !!currentUser?.roles.find((rol) => rol.siteId === "global");
		const handleClick = async (item: IImageUseItem) => {
			if (!item.structuredData) return;
			setSelectedStructuredData(item.structuredData.id, "global");
			setCurrentDataID(item.id);
			await getDataContent(item.id);
			if (isSiteView) {
				setCurrentSiteInfo(null);
				getUserCurrentPermissions();
			}
			setHistoryPush(`/data/${item.structuredData.id}/editor`);
		};
		return (
			<ItemGroup title="Global Simple Content" items={items.simpleData} onClick={handleClick} disabled={!hasGlobal} />
		);
	};

	const emptyStateProps = {
		title: "This image isn’t being used yet",
		message: "Add it to a content to see where it appears.",
	};

	const isNotUsed = !items?.globalPages.length && !items?.simpleData.length && !items?.sites.length;

	return (
		<S.Content>
			{loading ? (
				<Loading light={true} />
			) : isNotUsed ? (
				<S.EmptyStateWrapper data-testid="empty-state">
					<EmptyState {...emptyStateProps} />
				</S.EmptyStateWrapper>
			) : (
				<S.ListWrapper>
					{getPageList()}
					{getGlobalPageList()}
					{getGlobalStructuredDataList()}
				</S.ListWrapper>
			)}
		</S.Content>
	);
};

interface IProps {
	image: IImage;
	currentSiteID: number | null;
	selectedTab: "site" | "global";
	currentUser: IUser | null;
	setHistoryPush(page: string, isEditor?: boolean): Promise<void>;
	setCurrentPageID(currentPageID: number | null): ISetCurrentPageIDAction;
	getSite(siteID: number): Promise<void>;
	setCurrentDataID(id: number | null): void;
	setSelectedStructuredData(id: string, scope: string): void;
	getUserCurrentPermissions(): Promise<void>;
	setCurrentSiteInfo(currentSiteInfo: ISite | null): void;
	getDataContent(id: number): Promise<void>;
}

interface IInUseItems {
	sites: { id: number; title: string; pages: IImageUseItem[]; simpleContent: IImageUseItem[] }[];
	globalPages: IImageUseItem[];
	simpleData: IImageUseItem[];
}

export interface IImageUseItem {
	id: number;
	title: string;
	structuredData: { title: string; id: string } | null;
	date: Date;
}

const mapDispatchToProps = {
	setHistoryPush: appActions.setHistoryPush,
	setCurrentPageID: pageEditorActions.setCurrentPageID,
	getSite: sitesActions.getSite,
	setCurrentSiteInfo: sitesActions.setCurrentSiteInfo,
	setCurrentDataID: structuredDataActions.setCurrentDataID,
	setSelectedStructuredData: structuredDataActions.setSelectedStructuredData,
	getUserCurrentPermissions: usersActions.getUserCurrentPermissions,
	getDataContent: structuredDataActions.getDataContent,
};

const mapStateToProps = (state: IRootState) => ({
	currentSiteID: state.sites.currentSiteInfo && state.sites.currentSiteInfo.id,
	selectedTab: state.gallery.selectedTab,
	currentUser: state.users.currentUser,
});

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