import { ConfigService } from "../../../configService/index.mjs";
import { apiMutate } from "../../../utilities/useAxiosMutate.mjs";
import { LayoutUnit } from "../../../layout/LayoutUnit.mjs";
import { formatDataWithTimelineCategoryName } from "../functions/mttFunctions.mjs";
import { IconRenderer } from "../../../UI/templates/ui/renderers/IconRenderer.mjs";
import { MttYearTag } from "../ui/MttYearTag.mjs";
import { createTimeline } from "../timeline.mjs";
import { SummaryToken } from "../ui/SummaryToken.mjs";
import { TimelineTopRowFilter } from "../ui/TimelineTopRowFilter.mjs";
import { DateWrapper } from "../ui/DateWrapper.mjs";
import { CircleButton } from "../ui/CircleButton.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { CardContent, LinearProgress, Typography, makeStyles } from "@material-ui/core";
import { Link as Link$1 } from "react-router-dom";
import { RedEyeIcon } from "@fluentui/react-icons";
import PropTypes from "prop-types";
import { v4 } from "uuid";
import Skeleton from "@material-ui/lab/Skeleton";
//#region src/componentSystems/multiThreadTimeline/mttSummary/MttSummary.jsx
const useStyles = makeStyles((theme) => ({
	root: {},
	wrapper: {
		background: theme.palette.common.white,
		borderRadius: theme.spacing(.5),
		overflow: "hidden"
	},
	launch: { marginLeft: theme.spacing(8) }
}));
const MttSummary = (props) => {
	const { timelineApiMethodInstanceId, insightPath = "/mtt-main", params } = props;
	const [data, setData] = useState([]);
	const [timelineThreads, setTimelineThreads] = useState(null);
	const [timeline, setTimeline] = useState(null);
	const [loading, setLoading] = useState(false);
	const [filters, setFilters] = useState([]);
	const [allFilters, setAllFilters] = useState([]);
	const [compact, setCompact] = useState(true);
	const [filterListGroup, setFilterListGroup] = useState();
	const [filterKey, setFilterKey] = useState(v4());
	const classes = useStyles();
	const preloadLength = 11;
	const executeQueryInstance = useCallback(async (apiMethodInstanceId, data_0 = {}) => apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryInstance/${apiMethodInstanceId}`, { method: "post" }, { data: data_0 }), []);
	const summaryThreads = useMemo(() => {
		if (!timeline?.threads?.length) return [];
		setData(formatDataWithTimelineCategoryName(timeline.threads.filter((thread) => thread.inSummary)));
		return timeline.threads.filter((thread_0) => thread_0.inSummary);
	}, [timeline]);
	const summaryEvents = useMemo(() => {
		if (!summaryThreads.length) return [];
		return summaryThreads.map((st) => st.events).flat();
	}, [summaryThreads]);
	let filterItems = [];
	summaryThreads && summaryThreads.map((item) => {
		filterItems.push(item.name);
	});
	const addFilter = (filter) => {
		if (filters.includes(filter)) setFilters(filters.filter((e) => e !== filter));
		else setFilters([...filters, filter]);
	};
	const clearFilters = useCallback(() => {
		setFilters([]);
	}, []);
	useEffect(() => {
		const fetchTimelineThreads = async () => {
			const timelineResponse = await executeQueryInstance(timelineApiMethodInstanceId);
			if (timelineResponse?.status === 200) setTimelineThreads(timelineResponse?.data?.pageList || []);
		};
		fetchTimelineThreads();
	}, [executeQueryInstance, timelineApiMethodInstanceId]);
	useEffect(() => {
		const fetchThreadEvents = async () => {
			if (!timelineThreads) return null;
			setLoading(true);
			const promises = [];
			const threadList = [];
			timelineThreads.forEach((thread_1) => {
				promises.push(executeQueryInstance(thread_1.queryID, { ...params }));
			});
			await Promise.all(promises.map((p) => p.catch((e_0) => {
				setLoading(false);
				return e_0;
			}))).then((responses) => {
				responses.forEach((response, index) => {
					if (response.status === 200) {
						const timelineThread = timelineThreads[index];
						if (response?.data?.pageList) {
							response.data.pageList.forEach((evt) => evt.threadId = timelineThread.name);
							const thread_2 = {
								...timelineThread,
								events: response.data.pageList
							};
							threadList.push(thread_2);
						}
					}
				});
				setLoading(false);
			});
			setTimeline(createTimeline(threadList));
		};
		fetchThreadEvents();
	}, [
		executeQueryInstance,
		timelineThreads,
		params
	]);
	useEffect(() => {
		const filterList = summaryEvents && summaryEvents.map((item_0) => {
			return item_0.threadId;
		});
		setAllFilters(filterList);
		setFilters(filterList);
	}, [summaryEvents]);
	useEffect(() => {
		const filterListGroup_0 = [];
		summaryEvents && summaryEvents.map((item_1) => {
			filterListGroup_0.push({
				name: item_1.threadId,
				icon: item_1.icon,
				color: item_1.color
			});
		});
		const key = "name";
		const arrayUniqueByKey = [...new Map(filterListGroup_0.map((item_2) => [item_2[key], item_2])).values()];
		setFilterKey(v4());
		setFilterListGroup(arrayUniqueByKey);
	}, [summaryEvents]);
	const mappedToDetails = data && data.map((item_3) => item_3.dates).flat().map((item_4) => item_4.details).flat();
	const summaryLength = summaryThreads.length || preloadLength;
	const getMembers = (members) => {
		let events = [];
		return members.map((mem) => {
			const m = { ...mem };
			if (m.events && m.events.length) events = [...events, ...m.events];
			delete m.events;
			return m;
		}).concat(events.length ? getMembers(events) : events);
	};
	getMembers(summaryThreads);
	const dataConvertedFilter = mappedToDetails && mappedToDetails.filter((item_5) => filters?.includes(item_5.threadId));
	function groupByMonth(object) {
		let finalObject = [];
		object.forEach((el) => {
			let foundFlag = false;
			finalObject.forEach((foEl) => {
				if (foEl.month === el.date.split("/")[0] && foEl.year === el.date.split("/")[2]) {
					foEl.details.push(el);
					foundFlag = true;
				}
			});
			if (!foundFlag) finalObject.push({
				month: el.date.split("/")[0],
				year: el.date.split("/")[2],
				details: [el]
			});
		});
		return finalObject;
	}
	const SkeletonLoading = () => {
		return /* @__PURE__ */ React.createElement("div", { style: { marginRight: 48 } }, /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			justifyContent: "center"
		} }, /* @__PURE__ */ React.createElement(Skeleton, {
			variant: "circle",
			width: 30,
			height: 30
		})), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			justifyContent: "center"
		} }, /* @__PURE__ */ React.createElement(Skeleton, {
			variant: "rect",
			width: 1,
			height: 25
		})), /* @__PURE__ */ React.createElement(Skeleton, { variant: "text" }), /* @__PURE__ */ React.createElement(Skeleton, { variant: "text" }), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "sm" }), /* @__PURE__ */ React.createElement(Skeleton, {
			variant: "rect",
			width: 80,
			height: 6
		}));
	};
	const preLoading = [...Array(summaryLength).keys()].slice(1);
	const dataToSort = data && groupByMonth(dataConvertedFilter);
	const sorted = dataToSort.sort((a, b) => a.year - b.year || a.month - b.month);
	const getYears = [];
	data && dataToSort.map((item_6) => {
		getYears.push({ year: item_6.year });
	});
	const uniqueYears = [...new Set(getYears.map((item_7) => item_7.year))];
	return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: classes.wrapper }, loading && /* @__PURE__ */ React.createElement(LinearProgress, { color: "secondary" }), /* @__PURE__ */ React.createElement(CardContent, null, /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		position: "relative"
	} }, /* @__PURE__ */ React.createElement("div", { style: { flex: 1 } }, /* @__PURE__ */ React.createElement(Typography, { variant: "h6" }, "Timeline Summary"), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "md" })), /* @__PURE__ */ React.createElement("div", { style: { display: "flex" } }, /* @__PURE__ */ React.createElement("div", { key: filterKey }, /* @__PURE__ */ React.createElement(TimelineTopRowFilter, {
		compact,
		setCompact,
		onClose: () => setCompact(!compact),
		filterCall: (type) => addFilter(type),
		clear: clearFilters,
		filterList: filterItems && filterItems,
		filterListGroup: filterListGroup && filterListGroup
	})), /* @__PURE__ */ React.createElement("div", { className: classes.launch }, /* @__PURE__ */ React.createElement(CircleButton, {
		component: Link$1,
		to: {
			pathname: insightPath,
			state: { timelineApiMethodInstanceId }
		}
	}, /* @__PURE__ */ React.createElement(RedEyeIcon, null))))), /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		overflow: "scroll",
		direction: "rtl"
	} }, /* @__PURE__ */ React.createElement("div", { style: {
		direction: "ltr",
		display: "flex"
	} }, loading && preLoading.map((item_8) => {
		return /* @__PURE__ */ React.createElement(SkeletonLoading, { key: item_8 });
	}), uniqueYears.map((uniqueYear, index_0) => /* @__PURE__ */ React.createElement("div", { style: { display: "flex" } }, !loading && /* @__PURE__ */ React.createElement(MttYearTag, {
		year: true,
		count: 12
	}, uniqueYear), summaryEvents && data && sorted.map((item_9) => {
		if (item_9.year === uniqueYears[index_0]) return /* @__PURE__ */ React.createElement(DateWrapper, {
			months: Number(item_9.month),
			count: item_9.details.length
		}, item_9.details.map((item_10) => {
			return /* @__PURE__ */ React.createElement("div", { key: item_10.id }, /* @__PURE__ */ React.createElement(SummaryToken, {
				showMonth: true,
				months: [item_10.date],
				summary: true,
				icon: /* @__PURE__ */ React.createElement(IconRenderer, {
					removeMargin: true,
					value: {
						color: { hex: "#" + item_10.color },
						name: item_10.icon
					}
				}),
				showToken: true,
				status: item_10.data1 && item_10.data1.toString().trim() !== "" ? null : Number(item_10.data2),
				timelineItem: item_10.transactionType,
				title: item_10.shortDescription,
				date: item_10.date,
				dot: false,
				relative: true,
				amount: item_10.data1,
				month: Number(item_10.date.charAt(0)),
				user: item_10.data3,
				balance: item_10.data4,
				hidebackground: true
			}));
		}));
		else return null;
	}))))))));
};
MttSummary.propTypes = { timelineApiMethodInstanceId: PropTypes.string.isRequired };
//#endregion
export { MttSummary };

//# sourceMappingURL=MttSummary.mjs.map