export function deviceSetupFormPopup(device, sh_api) {
	device = Helper.unification.deviceFieldsUnification(device);

	return Modals.create("device-setup", {
		title: `Setup new device ${device.ip}`,
		body: modal => {

			let deviceProperties = "";
			for(let field in device) {
				if(field[0] == "_") continue;
				deviceProperties += `
					<tr class="table-row">
						<th>${field}: </th>
						<td>${device[field]}</td>
					</tr>
				`;
			}

			const deviceInfo = `
				<div class="block">
					<table class="table" style="border: 0">
						<tbody class="table-body">
							${deviceProperties}
						</tbody>
					</table>
				</div>
			`;

			return `
				<div class="row g-6">
					<div class="col device-info">
						${deviceInfo}
					</div>

					<div class="col setup-form w-100">
						<div class="block form-group">
							<label class="label">
								Device alias
								<i class="ph ph-asterisk"></i>
								<input type="text" name="alias" class="input" placeholder="Input alias">
							</label>
						</div>

						<div class="block form-group">
							<label class="label">
								Device name
								<i class="ph ph-asterisk"></i>
								<input type="text" name="name" class="input" placeholder="Input name">
							</label>
						</div>

						<div class="block form-group">
							<label class="label">
								About device
								<i class="ph ph-note-pencil"></i>
								<textarea class="input" name="description" placeholder="Input description"></textarea>
							</label>
						</div>

						<div class="alert-container"></div>
					</div>
				</div>
			`;
		},
		actions: modal => {
			const buttonCancel = Helper.template.createElement("button", { class: "btn btn-primary" }, "Cancel");
			buttonCancel.addEventListener("click", e => {
				modal.close();
			});

			const buttonSubmit = Helper.template.createElement("button", 
				{ class: "btn btn-success with-icon" }, 
				`<i class="ph ph-gear"></i> Setup`
			);

			buttonSubmit.addEventListener("click", e => {
				if(e.currentTarget.getAttribute("disabled")) {
					return false;
				}

				const inputs = {
					device_ip: device.ip
				};

				const setupForm = document.querySelector("#device-setup .setup-form");
				setupForm.querySelectorAll("input[type='text']").forEach(i => {
					i.dispatchEvent(
						new Event("input", { bubbles: true })
					);
				});

				if(setupForm.querySelectorAll(".label.error").length) {
					return false;
				}

				const inputElements = setupForm.querySelectorAll("input");
				const textareaElement = setupForm.querySelector("textarea");

				for(let input of inputElements) {
					inputs[input.getAttribute("name")] = input.value;
				}

				inputs[textareaElement.getAttribute("name")] = textareaElement.value;

				Helper.states.btnLoadingState(buttonSubmit, true);
				
				sh_api.devices.setup_new_device(inputs, (err, resp, meta) => {
					Helper.states.btnLoadingState(buttonSubmit, false);

					if(err?.type == "api_error") {
						console.error("ERR! sh_api.devices.setup_new_device", err.raw);

						if(err.raw?.failed_fields) {
							for(let errFieldName of err.raw.failed_fields) {
								modal.querySelector(`[name="${errFieldName}"]`).parentNode.classList.add("error");
							}
						}						

						if(err.raw?.msg) {
							const alertContainer = modal.querySelector(".setup-form .alert-container");
							alertContainer.innerHTML = "";
							alertContainer?.append(Helper.template.createAlert( "error", err.raw.msg ));
						}

						return false;
					}					

					if(!resp) {
						return false;
					}

					inputElements.forEach(i => i.value = "");
					textareaElement.value = "";
					modal.close();

					Screens.reinit();

					setTimeout(() => {
						Toasts.createSuccess("Setup successful", `Added new device <b>ID ${device.device_id}</b>`).show();
					}, 300);
				});
			});

			return [ buttonCancel, buttonSubmit ];
		},

		onready: modal => {
			const setupForm = modal.querySelector(".setup-form");
			setupForm.querySelectorAll("input").forEach(i => {
				i.addEventListener("input", e => {
					if(!e.currentTarget.value.length) {
						e.currentTarget.parentNode.classList.add("error");
						if(!e.currentTarget.parentNode.parentNode.querySelector(".input-info.error")) {
							e.currentTarget.parentNode.parentNode.append(Helper.template.createElement("div", {
								class: "input-info error"
							}, `<i class="ph ph-warning-circle"></i> Field cannot be empty`));
						}
					} else {
						e.currentTarget.parentNode.classList.remove("error");
						e.currentTarget.parentNode.parentNode.querySelector(".input-info.error")?.remove();
					}
				});
			});
		}
	})
}