import { ConfigService } from "../../../configService/index.mjs";
import { UdpSearchEnums } from "../../../enums/unitySystemEnums.mjs";
import { useAxiosMutate } from "../../../utilities/useAxiosMutate.mjs";
import { AmbientCard } from "../../../UI/surfaces/cards/AmbientCard/AmbientCard.mjs";
import { UdpBadge } from "../../../UI/fluent-web-components/UdpBadge.mjs";
import { UdpFlexbox } from "../../../UI/fluent-web-components/UdpFlexbox.mjs";
import { UdpPrimaryActionHeader } from "../../../UI/fluent-web-components/UdpPrimaryActionHeader.mjs";
import { useTransactionEngine } from "../../../utilities/transactions/useTransactionEngine.mjs";
import { UdpCalendar } from "../../../UI/templates/calendar/UdpCalendar.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/UdpTransactionCalendar.jsx
const CALENDAR_VIEW_OPTIONS = [
	"day",
	"week",
	"month"
];
const normalizeCalendarView = (value) => {
	const normalized = (value || "").toString().toLowerCase();
	return CALENDAR_VIEW_OPTIONS.includes(normalized) ? normalized : "week";
};
const buildDomainSearchField = (domainName, propertyName) => `${UdpSearchEnums.UdpBusinessDomainPrefix}.${domainName}.${propertyName}`;
function format12HourTime(date) {
	if (!date) return "";
	const hours = date.getHours();
	const minutes = date.getMinutes();
	const ampm = hours >= 12 ? "PM" : "AM";
	return `${hours % 12 || 12}:${minutes.toString().padStart(2, "0")} ${ampm}`;
}
const formatDate = (d) => d.toISOString().split("T")[0];
const STATUS_BG_COLORS = {
	warning: "#fff4ce",
	success: "#bdedbd",
	info: "#a9d3f2",
	gray: "#f5f5f5"
};
const DEFAULT_STATUS_BG = "#f5f5f5";
const UdpTransactionCalendar = (props) => {
	const { transactionTypeId, domainName, searchMethodObject, calendarViewConfiguration, openWorkflowActionTransaction, handleCalendarApiCallback, openAddTransaction, gridTitle, hideCreateTransaction = false, onShowGridView } = props;
	const domainStartDateProperty = calendarViewConfiguration?.domainStartDateProperty ?? "";
	const domainEndDateProperty = calendarViewConfiguration?.domainEndDateProperty ?? "";
	const { t } = useTranslation();
	const { getTransactionTypeLabel, transactionTypeStatusColorsMap, transactionTypePageConfiguration } = useTransactionEngine(transactionTypeId);
	const headerConfig = useMemo(() => {
		return {
			title: gridTitle || transactionTypePageConfiguration?.gridTitle || domainName,
			primaryAction: hideCreateTransaction || transactionTypePageConfiguration?.hideCreateTransaction ? void 0 : {
				label: transactionTypePageConfiguration?.createTransactionButtonLabel || `${domainName} Entry`,
				iconName: "add",
				onClick: () => openAddTransaction?.()
			},
			secondaryActions: [{
				iconOnly: true,
				iconName: "table",
				label: t("Grid View"),
				onClick: () => onShowGridView?.()
			}]
		};
	}, [
		gridTitle,
		domainName,
		hideCreateTransaction,
		transactionTypePageConfiguration,
		openAddTransaction,
		onShowGridView,
		t
	]);
	const [initialCalendarView] = useState(normalizeCalendarView(calendarViewConfiguration?.defaultCalendarViewType));
	const [calendarRange, setCalendarRange] = useState(null);
	const [calendarEvents, setCalendarEvents] = useState([]);
	const handleCalendarDatesSet = useCallback((rangeInfo) => {
		setCalendarRange({
			start: new Date(rangeInfo.start),
			end: new Date(rangeInfo.end)
		});
	}, []);
	const hasDomainDateConfig = Boolean(domainName && domainStartDateProperty && domainEndDateProperty);
	const searchObject = useMemo(() => {
		const baseFilters = [{
			searchField: "transactionTypeId",
			searchOperator: "=",
			searchValue: transactionTypeId
		}, {
			searchField: "isDeleted",
			searchOperator: "=",
			searchValue: false
		}];
		const dateRangeFilters = [];
		if (domainName && domainStartDateProperty && domainEndDateProperty && calendarRange?.start && calendarRange?.end) {
			const startField = buildDomainSearchField(domainName, domainStartDateProperty);
			const endField = buildDomainSearchField(domainName, domainEndDateProperty);
			const rangeStartFormatted = formatDate(calendarRange.start);
			const rangeEndFormatted = formatDate(calendarRange.end);
			dateRangeFilters.push({
				searchField: startField,
				searchOperator: "<=",
				searchValue: rangeEndFormatted
			}, {
				searchField: endField,
				searchOperator: ">=",
				searchValue: rangeStartFormatted
			});
		}
		const extraFilters = searchMethodObject?.filterElements || [];
		return {
			eagerLoad: true,
			getAll: true,
			...searchMethodObject || {},
			filterElements: baseFilters.concat(dateRangeFilters, extraFilters)
		};
	}, [
		transactionTypeId,
		searchMethodObject,
		domainName,
		domainStartDateProperty,
		domainEndDateProperty,
		calendarRange
	]);
	const [{ loading }, executeSearch] = useAxiosMutate(ConfigService.productV1ApiUrl, "UdpTransaction/search", { method: "post" });
	const legendItems = useMemo(() => Object.entries(transactionTypeStatusColorsMap ?? {}).map(([label, colorKey]) => ({
		label,
		color: STATUS_BG_COLORS[colorKey] ?? DEFAULT_STATUS_BG
	})), [transactionTypeStatusColorsMap]);
	const applyCalendarResponse = useCallback((response) => {
		if (response?.status !== 200) {
			setCalendarEvents([]);
			return;
		}
		setCalendarEvents((response.data?.pageList ?? []).map((transaction) => {
			const ebo = transaction?.entityBusinessObject ?? {};
			const startValue = ebo[domainStartDateProperty];
			const endValue = ebo[domainEndDateProperty];
			const eventStart = startValue ?? endValue;
			if (!eventStart) return null;
			const statusName = transaction?.udpTransactionUdpTransactionTypeStatus?.name;
			const statusBg = STATUS_BG_COLORS[transactionTypeStatusColorsMap?.[statusName]] ?? DEFAULT_STATUS_BG;
			return {
				title: getTransactionTypeLabel(transaction) ?? transaction?.entityBusinessKey ?? domainName,
				start: eventStart,
				...startValue && endValue ? { end: endValue } : {},
				backgroundColor: "transparent",
				borderColor: "transparent",
				extendedProps: {
					...transaction,
					statusBg
				}
			};
		}).filter(Boolean));
	}, [
		domainStartDateProperty,
		domainEndDateProperty,
		domainName,
		getTransactionTypeLabel,
		transactionTypeStatusColorsMap
	]);
	const refreshCalendarEvents = useCallback(async () => {
		if (!hasDomainDateConfig) return;
		if (!calendarRange?.start || !calendarRange?.end) return;
		try {
			applyCalendarResponse(await executeSearch({ data: searchObject }));
		} catch {
			setCalendarEvents([]);
		}
	}, [
		hasDomainDateConfig,
		calendarRange,
		searchObject,
		applyCalendarResponse
	]);
	useEffect(() => {
		if (!hasDomainDateConfig) return;
		if (!calendarRange?.start || !calendarRange?.end) return;
		let cancelled = false;
		executeSearch({ data: searchObject }).then((response) => {
			if (cancelled) return;
			applyCalendarResponse(response);
		}).catch(() => {
			if (!cancelled) setCalendarEvents([]);
		});
		return () => {
			cancelled = true;
		};
	}, [
		searchObject,
		hasDomainDateConfig,
		calendarRange,
		applyCalendarResponse
	]);
	useEffect(() => {
		if (!handleCalendarApiCallback) return;
		handleCalendarApiCallback(refreshCalendarEvents);
		return () => handleCalendarApiCallback(null);
	}, [handleCalendarApiCallback, refreshCalendarEvents]);
	return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(UdpPrimaryActionHeader, {
		title: headerConfig.title,
		primaryAction: headerConfig.primaryAction,
		secondaryActions: headerConfig.secondaryActions
	}), legendItems.length > 0 && /* @__PURE__ */ React.createElement("div", { style: { marginBottom: "4px" } }, /* @__PURE__ */ React.createElement(UdpFlexbox, {
		direction: "row",
		wrap: "wrap",
		justify: "flex-end"
	}, legendItems.map(({ label, color }) => /* @__PURE__ */ React.createElement(UdpBadge, {
		key: label,
		appearance: "ghost"
	}, /* @__PURE__ */ React.createElement("span", {
		slot: "start",
		style: {
			display: "inline-block",
			width: "var(--udp-spacing-md, 8px)",
			height: "var(--udp-spacing-md, 8px)",
			marginRight: "var(--udp-spacing-sm, 4px)",
			borderRadius: "50%",
			backgroundColor: color
		}
	}), label)))), /* @__PURE__ */ React.createElement(AmbientCard, { fullWidth: true }, /* @__PURE__ */ React.createElement(UdpCalendar, {
		initialView: initialCalendarView,
		toggleViewOptions: "dayGridDay,dayGridWeek,dayGridMonth",
		events: calendarEvents,
		eventOnclick: (info) => {
			openWorkflowActionTransaction(info.event.extendedProps);
		},
		eventContent: (info) => {
			info.event.start?.getTime();
			info.event.end?.getTime();
			const bg = info.event.extendedProps?.statusBg ?? "#f5f5f5";
			const opacity = 1;
			const startDate = info.event.start;
			const endDate = info.event.end;
			const startDay = startDate ? startDate.toDateString() : null;
			const endDay = endDate ? endDate.toDateString() : null;
			const segmentSpansMultipleDays = info.isStart && info.isEnd && endDay && startDay !== endDay;
			let timeRowHtml = "";
			if (segmentSpansMultipleDays) timeRowHtml = `<div style="display:flex; justify-content:space-between; gap:8px; word-wrap: break-word; white-space: normal;"><b>${format12HourTime(startDate)}</b><b>${format12HourTime(endDate)}</b></div>`;
			else if (info.isStart && info.isEnd) timeRowHtml = `<div style="word-wrap: break-word; white-space: normal;"><b>${format12HourTime(startDate)}${endDate ? " - " + format12HourTime(endDate) : ""}</b></div>`;
			else if (info.isStart) timeRowHtml = `<div style="word-wrap: break-word; white-space: normal;"><b>${format12HourTime(startDate)}</b></div>`;
			else if (info.isEnd) timeRowHtml = `<div style="word-wrap: break-word; white-space: normal; text-align:right;"><b>${format12HourTime(endDate)}</b></div>`;
			return { html: `
              <div style="width:100%; cursor:pointer; padding:5px; background-color: ${bg}; color: #242424; opacity: ${opacity};">
                ${timeRowHtml}
                <div style="word-wrap: break-word; white-space: normal;">
                  ${info.event.title + " - " + info.event.extendedProps.entityBusinessObject[calendarViewConfiguration?.domainPropertyToDisplay]}
                </div>
              </div>
            ` };
		},
		width: "auto",
		height: 700,
		dayHeaders: true,
		datesSet: handleCalendarDatesSet
	})));
};
//#endregion
export { UdpTransactionCalendar as default };

//# sourceMappingURL=UdpTransactionCalendar.mjs.map