import { Controller } from 'stimulus';
import { sendReserve } from "./../components/record";
import Inputmask from "inputmask";

const validator = require('./../components/validator.js');
const helper = require('./../components/helper.js');
const loader = require("./../components/loader.js");
const Cookies = require('js-cookie');

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="signin" attribute will cause
 * this controller to be executed. The name "signin" comes from the filename:
 * signin_controller.js -> "signin"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
	connect() {
		loader.loadSDK('signin').then(function (webSDK) {
			webSDK.on('init', function() {
				if (location.hash == '#recovery') {
					const popup = document.getElementById('popup');
					
					popup.dataset.controller = 'resetPassword';
					popup.dataset.recovery = true;
					
					$(popup).modal('show');    
				}
			})
		})
	}

	esia() {
		const element = this.element
		
		element.addEventListener('click', function() {
			const currentUrl = window.location.href;
			const redirectUrl = helper.addUrlParam(currentUrl, 'esia', 'true');

			window.webSDK.loadLoginView({
				authType: "esia",
				redirectUrl: redirectUrl,
				newWindow: false
			});
		});
	}

	login() {
		function renderAuth(msg = false) {
			var popup = document.getElementById('popup');
			
			// Сохраняем данные записи перед очисткой popup (если они есть)
			if (popup && popup.dataset.reserve === 'true') {
				const reserveData = {
					specialistid: popup.dataset.specialistid,
					filialid: popup.dataset.filialid,
					depnum: popup.dataset.depnum,
					schedident: popup.dataset.schedident,
					workDate: popup.dataset.workDate,
					time: popup.dataset.time,
					onlinemode: popup.dataset.onlinemode,
					comment: popup.dataset.comment,
					docname: popup.dataset.docname,
					address: popup.dataset.address,
					company: popup.dataset.company,
					rnum: popup.dataset.rnum
				};
				// Сохраняем только если есть хотя бы одно поле
				if (reserveData.specialistid || sessionStorage.getItem('reserveData')) {
					sessionStorage.setItem('reserveData', JSON.stringify(reserveData));
					sessionStorage.setItem('reserveFlag', 'true');
				}
			}
			
			var popupBody = popup.querySelector('.modal-title');
			popupBody.innerText = "Авторизация";
			
			popupBody = popup.querySelector('#popup-body');
			popupBody.innerHTML = '';
			popupBody.dataset.controller = 'signin';

			var validMessage = document.createElement('div');
			validMessage.classList = "msg-valid valid-message alert alert-danger d-none";
			
			if (msg) {
				validMessage.innerHTML = msg;
				validMessage.classList.remove('d-none');
			}

			popupBody.append(validMessage);

			var username = document.createElement('input');
			username.type = "text";
			username.classList = "form-control border-radius";
			username.required = "true";
			username.autofocus = "off";
			username.autocomplete = "off";
			username.id = "username";

			var groupPrepend = document.createElement('div');
			groupPrepend.classList = 'input-group-prepend';

			var select = document.createElement('select');
			select.classList = "input-group-text";

			var optionEmail = document.createElement('option');
			optionEmail.value = "email";
			optionEmail.innerText = "Email";
			select.append(optionEmail);

			var optionPhone = document.createElement('option');
			optionPhone.value = "phone";
			optionPhone.innerText = "Телефон";
			select.append(optionPhone);
			groupPrepend.append(select);

			select.addEventListener('change', function() {
				const selectedValue = this.value;

				if (selectedValue === 'email') {
					username?.inputmask.remove();
					username.type = "email";
				} else if (selectedValue === 'phone') {
					username.type = "text";
					Inputmask({ mask: '79999999999' }).mask(username);
				}
			});

			var inputGroup = document.createElement('div');
			inputGroup.classList = "input-group";
			inputGroup.append(groupPrepend);
			inputGroup.append(username);

			var formGroup = document.createElement('div');
			formGroup.classList = "form-group";

			var validUsername = document.createElement('div');
			validUsername.classList = "msg-valid valid-username";
			formGroup.append(inputGroup);
			formGroup.append(validUsername);
			popupBody.append(formGroup);

			var password = document.createElement('input');
			password.placeholder = "Пароль";
			password.type = "password";
			password.classList = "form-control border-radius";
			password.required = "true";
			password.id = "password";
			password.addEventListener('keydown', function(evn) {
				if (evn.code == 'Enter') {
					loader.btnLoader(btnSubmit, true);
					submit(window.webSDK, username, password, popupBody);
				}
			});

			var formGroup = document.createElement('div');
			formGroup.classList = "form-group";
			formGroup.dataset.controller = 'passwordShow';
			formGroup.append(password);

			var validPassword = document.createElement('div');
			validPassword.classList = "msg-valid valid-password";
			formGroup.append(validPassword);
			popupBody.append(formGroup);


			/* политика */
			var div = document.createElement('div');
			div.classList = 'form-group';

			var formCheck = document.createElement('div');
			formCheck.classList = 'form-check';
			div.append(formCheck);

			var accept = document.createElement('input');
			accept.classList = "form-check-input";
			accept.id = "accept";
			accept.checked = false;
			accept.type = "checkbox";
			formCheck.append(accept);

			var license = helper.getLicenseLink(Cookies.get('region'));
			var label = document.createElement('label');
			label.setAttribute('for' , 'accept');
			label.innerHTML = `ознакомлен(а) <a class="underline" href="${license}" target="_blank">с условиями политики в отношении обработки персональных данных</a>`;
			
			formCheck.append(label);
			
			var validAccept = document.createElement('div');
			validAccept.classList = 'msg-valid valid-accept';
			div.append(validAccept);

			popupBody.append(div)

			/* согласие */

			var formCheck = document.createElement('div');
			formCheck.classList = 'form-check';
			div.append(formCheck);

			var acceptPerson = document.createElement('input');
			acceptPerson.classList = "form-check-input";
			acceptPerson.id = "acceptPerson";
			acceptPerson.checked = false;
			acceptPerson.type = "checkbox";
			formCheck.append(acceptPerson);

			var licensePerson = helper.getLicensePersonLink();
			var labelPerson = document.createElement('label');
			labelPerson.setAttribute('for' , 'acceptPerson');
			labelPerson.innerHTML = `даю согласие <a class="underline" href="${licensePerson}" target="_blank">на обработку персональных данных</a>`;
			
			formCheck.append(labelPerson);
			
			var validAcceptPerson = document.createElement('div');
			validAcceptPerson.classList = 'msg-valid valid-acceptPerson';
			div.append(validAcceptPerson);

			popupBody.append(div)

			var btnSubmit = document.createElement('button');
			btnSubmit.type = "button";
			btnSubmit.innerHTML = "Войти";
			btnSubmit.classList = "btn btn-outline-secondary submit";
			btnSubmit.addEventListener('click', function() {
				let invalid = false;

				if (validator.checkAccept(accept, validAccept)) {
					invalid = true;
				}

				if (validator.checkAccept(acceptPerson, validAcceptPerson)) {
					invalid = true;
				}

				if (invalid == false) {
					loader.btnLoader(btnSubmit, true);
					submit(window.webSDK, username, password, popupBody);
				}
			});

			var helpLink = document.createElement('a');
			helpLink.classList = 'btn my-0';
			helpLink.dataset.controller = 'serviceDesk';
			helpLink.style = 'font-size: 21px;';
			helpLink.innerHTML = `<i class="fa fa-info-circle" aria-hidden="true"></i>`;

			var guLink = document.createElement('a');
			guLink.classList = 'btn my-0';
			guLink.dataset.action = 'signin#esia';
			guLink.innerHTML = `<img src="${helper.getHostname()}/images/eisa.jpg" width="30" alt="EISA">`;

			var forgetLink = document.createElement('button');
			forgetLink.classList = 'btn';
			forgetLink.dataset.controller = 'resetPassword';
			forgetLink.innerHTML = 'Забыли пароль?';

			var footer = document.createElement('div');
			footer.classList = 'modal-footer px-0';

			footer.append(helpLink);
			footer.append(guLink);
			footer.append(forgetLink);
			footer.append(btnSubmit);
			popupBody.append(footer);
		}

		renderAuth();

		var popup = document.getElementById('popup');
		if (popup && typeof $(popup).modal !== 'undefined') {
			$(popup).modal('show');
		}

		function submit(webSDK, username, password, popupBody) {
			popupBody.querySelectorAll('.msg-valid').forEach(function (e) {
				e.classList.add('d-none');
				e.innerHTML = '';	
			});

			webSDK.loginClient({
				login: username.value,
				pass: password.value
			}).then(function(user) {

				if (user.result && user.result.checkdata && typeof user.result.checkdata.pToken !== 'undefined') {
					changeTempPassword(user.result);
					return false;
				}

				let data = {
					user: user,
					uid: user.id
				}
								
				if (window.location.pathname !== '/login') {
					data = {
						user: user,
						uid: user.id,
						redirectFrom: window.location.href
					}
				}

				var popup = document.getElementById('popup');

				if (popup.dataset.reserve === "true") {
					data.redirectFrom = helper.getHostname() + '/case-history#doctor-success';
				}

				$.ajax({
					method: "POST",
					crossDomain: true,
					url: "/api/authenticated",
					contentType: "application/x-www-form-urlencoded",
					dataType: "json",
					data: data,
					success(response) {
						if (response.data.success == true) {
							// Восстанавливаем данные записи из sessionStorage если они были сохранены
							const reserveFlag = popup.dataset.reserve === "true" || sessionStorage.getItem('reserveFlag') === 'true';
							
							if (reserveFlag) {
								// Восстанавливаем данные из sessionStorage
								const reserveDataStr = sessionStorage.getItem('reserveData');
								if (reserveDataStr) {
									try {
										const reserveData = JSON.parse(reserveDataStr);
										Object.keys(reserveData).forEach(key => {
											if (reserveData[key] !== undefined && reserveData[key] !== null) {
												popup.dataset[key] = reserveData[key];
											}
										});
										console.log('Данные записи восстановлены из sessionStorage:', reserveData);
									} catch (e) {
										console.error('Ошибка при восстановлении данных из sessionStorage:', e);
									}
								}
								
								// Устанавливаем флаг reserve если его нет
								popup.dataset.reserve = 'true';
								
								// Проверяем наличие всех необходимых полей перед вызовом sendReserve
								const requiredFields = ['specialistid', 'filialid', 'depnum', 'schedident', 'workDate', 'time'];
								const missingFields = requiredFields.filter(field => !popup.dataset[field]);
								
								if (missingFields.length > 0) {
									console.error('Отсутствуют необходимые поля для записи:', missingFields);
									alert('Ошибка: не удалось восстановить данные для записи. Пожалуйста, попробуйте записаться снова.');
									// Очищаем sessionStorage
									sessionStorage.removeItem('reserveData');
									sessionStorage.removeItem('reserveFlag');
									// Делаем обычный редирект
									var parser = document.createElement('a');
									parser.href = response.data.redirect;
									window.location.replace(helper.getHostname() + parser.pathname + parser.search);
									return;
								}
								
								// Очищаем sessionStorage после успешного восстановления
								sessionStorage.removeItem('reserveData');
								sessionStorage.removeItem('reserveFlag');
							}
							
							if (window.bitrix === true) {
								if (reserveFlag) {
									// Для bitrix тоже нужно вызвать sendReserve для создания записи
									// Сообщение покажет сам sendReserve после успешной записи
									sendReserve(popup);
								} else {
									// Если не было флага reserve, показываем обычное сообщение
									popup.querySelector('.modal-title').innerHTML = 'Запись на прием';
									var message = '<p>Спасибо, Вы успешно записались на прием. </br>';
									message += popup.dataset.comment + ', ';
									message += popup.dataset.workDate + ' ' + popup.dataset.time + '</br></p>';
									message += '<p>Вы всегда можете отменить или перенести запись в личном кабинете по ссылке: ';
									message += '<a href="https://cabinet.sovamed.ru" >https://cabinet.sovamed.ru</a></p>';
									popup.querySelector('#popup-body').innerHTML = message;
								}
							} else {
								if (reserveFlag) {
									// Если нужно создать запись, вызываем sendReserve, который сам сделает редирект
									sendReserve(popup);
								} else {
									// Иначе делаем обычный редирект
									var parser = document.createElement('a');
									parser.href = response.data.redirect;
									window.location.replace(helper.getHostname() + parser.pathname + parser.search);
								}
							}
						}
					}
				});
			}).catch(function(error) {

				helper.sendRequest({
					data: {'error': error, login: username.value, method: 'loginClient'}
				}, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");

				var btnSubmit = popupBody.querySelector('button.submit');
				loader.btnLoader(btnSubmit, false);

				for (var prop in error.data) {
					if (error.data[prop]) {
						var el = popupBody.querySelector('.valid-' + prop)
						el.classList.remove('d-none');
						el.innerHTML = error.data[prop];
					}
				}
			});
		};   	
	 
		function changeTempPassword(response) {
			var popup = document.getElementById('popup');
			var popupBody = popup.querySelector('.modal-title')
				.innerText = "Смена временного пароля";
			
			var popupBody = popup.querySelector('#popup-body');
			popupBody.innerHTML = '';

			var validMessage = document.createElement('div');
			validMessage.classList = "msg-valid valid-message alert alert-warning";
			validMessage.innerHTML = response.checkdata.msg;
			popupBody.append(validMessage);

			var password = document.createElement('input');
			password.placeholder = "Новый пароль";
			password.type = "password";
			password.classList = "form-control border-radius";
			password.required = "true";
			password.id = "password";			
			
			var formGroup = document.createElement('div');
			formGroup.classList = "form-group";
			formGroup.append(password);

			var validPassword = document.createElement('div');
			validPassword.classList = "msg-valid valid-password";
			formGroup.append(validPassword);
			popupBody.append(formGroup);

			var confirm = document.createElement('input');
			confirm.placeholder = "Подтверждение";
			confirm.type = "password";
			confirm.classList = "form-control border-radius";
			confirm.required = "true";
			confirm.id = "confirm";			
			
			var formGroup = document.createElement('div');
			formGroup.classList = "form-group";
			formGroup.append(confirm);

			var validConfirm = document.createElement('div');
			validConfirm.classList = "msg-valid valid-confirm";
			formGroup.append(validConfirm);
			popupBody.append(formGroup);

			var btnSubmit = document.createElement('button');
			btnSubmit.type = "button";
			btnSubmit.innerHTML = "Сменить пароль";
			btnSubmit.classList = "btn btn-outline-secondary submit";
			btnSubmit.addEventListener('click', function() {
				if (/^[\u0400-\u04FF]+$/.test(password.value)) {
					popupBody.querySelector('.valid-password')
						.innerHTML = '<span class="text-danger">Поле не должно содержать кириллицы</span>';
					
					return false;
				} else {
					popupBody.querySelector('.valid-password').innerHTML = '';
				}

				if (password.value !== confirm.value) {
					popupBody.querySelector('.valid-confirm')
						.innerHTML = '<span class="text-danger">Подтверждение не совпадает с паролем</span>';
					
					return false;
				} else {
					popupBody.querySelector('.valid-confirm').innerHTML = '';	
				}

				loader.btnLoader(btnSubmit, true);

				window.webSDK.changeTempPassword({
					pwdToken: response.checkdata.pToken,
					password: password.value,
					confirm: confirm.value
				}).then(function(resolve) {
					renderAuth(resolve.data.success);		
				}).catch(function(e) {
					helper.sendRequest({
						data: {'error': e, method: 'changeTempPassword'}
					}, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
					var btnSubmit = popupBody.querySelector('button.submit');
					loader.btnLoader(btnSubmit, false);

					for (var prop in e.data.errors) {
						if (e.data.errors[prop]) {
							var el = popupBody.querySelector('.valid-' + prop.split('.')[1])
							el.classList.remove('d-none');
							el.innerHTML = e.data.errors[prop][0];
						}
					}
				})
			});

			var footer = document.createElement('div');
			footer.classList = 'modal-footer';
			footer.append(btnSubmit);
			popupBody.append(footer);
	  }
  }
}