<template>
	<modal
		@close="closeLanguageModal"
		ref="wccLanguagesModal"
		class="wcc-app-modal-languages"
	>
		<template v-slot:header>
			<h4>{{ $i18n.__("Add language", "webtoffee-cookie-consent") }}</h4>
		</template>
		<template v-slot:body>
			<div class="wcc-row">
				<div class="wcc-col-12">
					<div
						class="wcc-dropdown-languages"
					>
						<div class="wcc-dropdown-search-input">
							<input
								type="text"
								class="wcc-form-control"
								v-model="searchText"
								:placeholder="$i18n.__('Search...', 'webtoffee-cookie-consent')"
								ref="wccSearchInput"
							/>
						</div>
						<div class="wcc-language-list-container" :style="{ maxHeight: languageListMaxHeight }">
							<ul>
								<li v-for="item in filterLanguages" :key="item.code">
									<div class="wcc-form-group">
										<input
											type="checkbox"
											:id="'wcc-checkbox-language-' + item.code"
											:value="item.code"
											v-model="tempSelectedLanguages"
											:disabled="isExist(item.code)"
											:data-test-id="`wcc-add-language-checkbox-${item.code}`"
										/>
										<label
											:for="'wcc-checkbox-language-' + item.code"
											class="wcc-label"
											:data-test-id="`wcc-add-language-label-${item.code}`"
											>{{ item.name }}&nbsp;({{ item.code }})</label
										>
									</div>
									<span
										class="wcc-language-notice"
										v-if="!isTranslated(item.code) && isAdded(item.code)"
										:data-test-id="`wcc-add-language-notice-${item.code}`"
									>
										<img src="@/assets/action-alert.svg" alt="alert-icon" />
										<span class="wcc-notice-inner">
											{{
												$i18n.__("Translations not available", "webtoffee-cookie-consent")
											}}
										</span>
									</span>
								</li>
							</ul>
						</div>
					</div>
				</div>
			</div>
		</template>
		<template v-slot:footer>
			<div class="wcc-row">
				<div class="wcc-col-12">
					<Transition>
						<notice
							type="warning"
							v-show="!checkIfTranslated && visible"
							style="margin-top: 15px"
						>
							<p>
								{{
									$i18n.__(
										"Note: Translations are not available for some of the languages you have added, so the banner content that has not been translated will be displayed in English unless you add translations for these languages manually.",
										"webtoffee-cookie-consent"
									)
								}}
							</p>
						</notice>
					</Transition>
				</div>
			</div>
			<div class="wcc-app-modal-actions wcc-justify-end">
				<div class="wcc-action-languages wcc-actions-group wcc-justify-end">
					<button class="wcc-button wcc-button-secondary" @click="close" :data-test-id="`wcc-add-language-cancel-button`">
						Cancel
					</button>
					<button
						class="wcc-button wcc-button-primary"
						@click="addSelectedLanguages"
						:disabled="disabled"
						:data-test-id="`wcc-add-language-save-button`"
					>
						Add
					</button>
				</div>
			</div>
		</template>
	</modal>
</template>
<script>
import Modal from "@/components/Modal.vue";
import languages from "@/modules/languages/helpers/utils";
import Notice from "@/components/elements/Notice.vue";

export default {
	name: "LanguageSelector",
	components: {
		Modal,
		Notice,
	},
	data() {
		return {
			searchText: "",
			tempSelectedLanguages: [],
			languages: {},
			currentTab: "layout",
			searchLanguages: [],
			filteredLanguages: [],
			visible: true,
			languageListMaxHeight: "300px",
		};
	},
	methods: {
		showIcon(tab) {
			return !!tab.icon;
		},
		async open() {
			await this.$refs.wccLanguagesModal.show();
			this.$refs.wccSearchInput.focus();
			this.searchText = "";
			this.getConfiguredLanguages();
		},
		close() {
			this.$refs.wccLanguagesModal.close();
		},
		closeLanguageModal() {
			this.tempSelectedLanguages = this.selectedLanguages;
		},
		getAvailableLanguages() {
			this.languages = this.$store.state.languages.available;
		},
		getConfiguredLanguages() {
			this.tempSelectedLanguages = this.selectedLanguages;
		},
		async addSelectedLanguages() {
			try {
				this.$store.dispatch(
					"languages/setSelected",
					this.tempSelectedLanguages
				);
				await this.$store.dispatch("languages/saveSelected");
				this.close();
				await this.purgeCache();
				await this.$store.dispatch("banners/reInit");
				await this.$store.dispatch("cookies/reInit");
			} catch (error) {
				console.log(error);
				this.$root.$emit("triggerNotification", {
					type: "error",
					message: this.$i18n.__(
						"Problem occurred while adding languages. Please try again later!",
						"webtoffee-cookie-consent"
					),
				});
			}
		},
		isTranslated(lang = "en") {
			const supported = languages.getTranslatedLanguages();
			return supported.includes(lang);
		},
		isAdded(lang = "en") {
			const selected = this.tempSelectedLanguages;
			return selected.includes(lang);
		},
		isExist(lang = "en") {
			const selected = this.selectedLanguages;
			return selected.includes(lang);
		},
		toggleDropDown() {
			this.visible = !this.visible;
		},
		checkAndSetMaxHeight() {
			this.$nextTick(() => {
				const warningElement = document.querySelector('.wcc-admin-notice-warning');
				if (warningElement && warningElement.style.display === 'none') {
					this.languageListMaxHeight = "300px";
				} else {
					this.languageListMaxHeight = "190px";
				}
			});
		},
	},
	computed: {
		currentTabComponent: function () {
			return `tab-${this.currentTab.toLowerCase()}`;
		},
		selectedLanguages: function () {
			return this.$store.state.languages.selected;
		},
		filterLanguages() {
			if (this.languages.length > 0) {
				let selected = [],
					others = [];
				let languages = [];
				this.languages.forEach((item) => {
					if (this.selectedLanguages.includes(item.code)) {
						selected.push(item);
					} else {
						others.push(item);
					}
				});
				languages = selected.concat(others);
				return languages.filter((item) => {
					return item.name
						.toLowerCase()
						.includes(this.searchText.toLowerCase());
				});
			}
			return [];
		},
		disabled() {
			const diff = this.tempSelectedLanguages.filter(
				(lang) => !this.selectedLanguages.includes(lang)
			);
			return !diff.length;
		},
		checkIfTranslated() {
			let translated = true;
			this.tempSelectedLanguages.forEach((lang) => {
				if (this.isTranslated(lang) === false) {
					translated = false;
					return false;
				}
			});
			this.checkAndSetMaxHeight();
			return translated;
		},
	},
	watch: {},
	mounted() {
		this.getAvailableLanguages();
		this.getConfiguredLanguages();
	},
};
</script>
<style lang="scss" scoped>
@include wrap-class() {
	.wcc-app-modal-languages {
		.wcc-app-modal {
			width: 590px;
			height: 466px;
			border-radius: 12px;
			border: 1px solid #E9EBF8;
			background: #FFF;
			box-shadow: 0px 3px 82px 0px rgba(43, 69, 88, 0.20);
		}
		.wcc-app-modal-body {
			height: 380px;
		}
		.wcc-button-close {
			display: none;
		}
		.wcc-app-modal-header {
			border-bottom : none;
		}
		.wcc-admin-notice.wcc-admin-notice-warning {
			border-radius: 4px;
			background: var(--warning-w-50, #FBF6E8);
			
			.wcc-admin-notice-message p {
				color: #997410;
			}
		}
	}
	.wcc-dropdown-languages {
		&.open {
			.wcc-dropdown-anchor {
				border-bottom-right-radius: 0px;
				border-bottom-left-radius: 0px;
			}
		}
		ul {
			li {
				display: flex;
				align-items: center;
				min-height: 40px;
				&:hover {
					background: transparent;
				}
			}
		}
		.wcc-dropdown-content {
			border-top: none;
			border-top-right-radius: 0px;
			border-top-left-radius: 0px;
		}
		.wcc-dropdown-search-input {
			margin-bottom: 0;
			input[type="text"] {
				background-image: url("~@/assets/search.svg");
				background-position: 10px 12px;
				background-repeat: no-repeat;
				padding: 5px 0 5px 33px;
				z-index: 1;
				background-size: 18px;
				display: flex;
				align-items: center;
				gap: 6px;
				flex-shrink: 0;
				border-radius: 33px;
				border: 1.5px solid var(--light-color-border-focused, #388BFF);
				background-position: 15px 12px; /* Adjust the horizontal and vertical values for margin */
			}
		}
		.wcc-dropdown-content {
			padding: 0px;
			ul li {
				padding: 0px 10px;
			}
		}
		.wcc-label {
			margin-bottom: 0;
			padding: 10px 5px;
		}
		.wcc-form-group {
			margin-bottom: 5px;
		}
		.wcc-dropdown-content {
			position: relative;
		}
		.wcc-language-notice {
			background-color: #fff;
			border-radius: 3px;
			color: #997410;
			font-size: 13px;
			margin-bottom: 0;
			margin-right: 12px;
			padding: 5px;
			display: flex;
			align-items: center;
			img {
				height: 13px;
				margin-right: 5px;
			}
			margin-bottom: 5px;
		}
	}
	.wcc-action-languages {
		width: 100%;
		box-sizing : border-box;
	}
	.wcc-app-modal-actions button {
		width: 50%;
	}
	.wcc-app-modal-actions .wcc-button.wcc-button-secondary, .wcc-app-modal-actions .wcc-button.wcc-button-secondary:hover {
		background-color: #FFF;
		border-color: #3157A6;
		color: #3157A6;
	}
	.wcc-app-modal-footer .wcc-app-modal-actions .wcc-action-languages button:first-child {
		margin-right: 10px;
	}
	.wcc-language-list-container {
		max-height: 310px; /* Adjust the height as needed */
		overflow-y: scroll;
		margin: 0px 20px 0px 20px;
		min-height: 190px;
	}
}
.wcc-app-modal-languages .wcc-app-modal-footer {
	padding: 0px 20px;;
}
</style>