import { placeInArea } from "./areas-placeto-component.js";

function initEditedFields(sh_api, area, modal) {
	const editedFields = [
		{
			payloadFieldName: "display_name",
			selector: ".display-name",
			methName: "update_display_name",
			originalValue: area.display_name,
			isMultiString: false
		},
		{
			payloadFieldName: "new_alias",
			selector: ".alias",
			methName: "update_alias",
			originalValue: area.alias,
			isMultiString: false
		},
	];

	for(let editedField of editedFields) {
		const edit = editableString(modal.querySelector(editedField.selector));
		edit.editableString.onChange(component => {
			const payload = {
				area_id: area.id,
			};

			payload[editedField.payloadFieldName] = component.value;

			sh_api.areas[editedField.methName](payload, (err, resp, meta) => {
				if(err || !resp || !resp.status) {
					console.error(`sh_api.areas.${editedField.methName}`, err);
					edit.editableString.setValue(editedField.originalValue);

					return Toasts.createError(
						err?.message ?? "Error updating", 
						err.raw?.msg ?? `Error of ${editedField.payloadFieldName} updating`
					).show();
				}

				if(resp.status == true) {
					DataProvider.invalidatePrefix("raw.areas");
					Screens.reinit();
				}
			});
		});
	}
}

export function areaDetailsModal(area, sh_api) {
	area = DataProvider.getRaw(`areas.${area.id}`) ?? area;

	console.log("areaDetailsModal", area);

	return Modals.create("area-details-modal", {
		title: `<i class="ph ph-map-trifold normalize"></i> ${area.display_name}`,
		body: modal => {
			const entityData = area;

			const fieldClassMap = {
				parent_id: "place-in-area-container",
				display_name: "display-name",
				alias: "alias-view-container"
			};

			const wrapToContainer = (field, value) => {
				const map = {
					alias: `<i class="ph ph-link-simple-break"></i> <span class="alias">{{value}}</span>`,
					create_at: value => Helper.unification.formatDate(value),
					update_at: value => Helper.unification.formatDate(value),
					schema: "<span class='text-mute'>Nothing yet</span>",
				}

				return map[field] 
					? (typeof map[field] == "function" ? map[field](value) : map[field].replaceAll("{{value}}", value))
					: value; 
			}

			let properties = "";
			for(let field in entityData) {
				let fieldValueClass = fieldClassMap[field] ?? "";

				properties += `
					<tr class="table-row">
						<th>${field}: </th>
						<td class="${fieldValueClass}">${wrapToContainer(field, entityData[field])}</td>
					</tr>
				`;
			}

			return `
				<table class="table" style="border: 0">
					<tbody class="table-body">
						${properties}
					</tbody>
				</table>
			`;
		},
		actions: modal => {
			const btnCancel = Helper.template.createElement("button", {
				class: "btn btn-primary"
			}, "Close");

			const btnRemove = Helper.template.createElement("button", {
				class: "btn btn-danger with-icon"
			}, `<i class="ph ph-trash"></i> Remove`);

			btnCancel.addEventListener("click", e => {
				modal.close();
			});

			btnRemove.addEventListener("click", e => {
				Helper.states.btnLoadingState(btnRemove, true);

				confirmPopup(
					`Are you sure you want to remove this area? <b>${area.display_name}</b>`, 
					() => {
						sh_api.areas.remove(
							area.id,
							(err, data, meta) => {
								
								Helper.states.btnLoadingState(btnRemove, false);
								console.log("Was removed");

								DataProvider.invalidatePrefix("raw.areas");
								modal.close();
								Screens.reinit();

								setTimeout(() => {
									Toasts.createSuccess(
										"Removed",
										`Area: ${area.display_name}`
									).show();
								}, 300);
							}
						);
				}, 
				() => {
					Helper.states.btnLoadingState(btnRemove, false);
					console.log("CANCELED");
				});
			});

			return [ btnCancel, btnRemove ];
		},
		onready: modal => {
			placeInArea(
				sh_api,
				modal.querySelector(".place-in-area-container"),
				"area",
				area.id,
				area.parent_id
			);

			initEditedFields(sh_api, area, modal);
		}
	});
}