<template>
	<div
		class="wcc-section wcc-section-cookies wcc-zero--padding wcc-zero--margin"
	>
		<div class="wcc-section-header">
			<div class="wcc-row wcc-justify-between wcc-align-center">
				<div class="wcc-col-9">
					<div class="wcc-section-title wcc-align-center">
						<h3>Consent history</h3>
						<base-switch v-model="consentLog" name="consent-log-toggle" />
					</div>
					<p>
						{{
							$i18n.__(
								"View visitor consents and download proof of compliance with privacy regulations and laws.",
								"webtoffee-cookie-consent"
							)
						}}
					</p>
				</div>
				<div class="wcc-col-3 wcc-justify-end">
					<base-button
						v-if="!isConsentEmpty"
						class="wcc-button wcc-button-outline-blue"
						ref="wccButtonExportConsentLog"
						@click.native="exportLog"
						style="margin-left: 15px"
						:data-test-id="`wcc-consent-logs-export-button`"
					>
						{{ $i18n.__("Export as CSV", "webtoffee-cookie-consent") }}
					</base-button>
					<div class="wcc-consent-logs-more-actions" v-if="!isConsentEmpty">
						<button
							data-type="icon"
							class="wcc-button wcc-button-no-style"
							@click.stop="toggleActionsMenu"
							:data-test-id="`wcc-consent-logs-more-actions-button`"
						>
							...
						</button>
						<div class="wcc-consent-logs-more-actions-list" v-show="showActionsMenu">
							<ul>
								<li>
									<base-popper
										ref="wccButtonDeleteConsentLog"
										:content=" $i18n.__( 'Delete history','webtoffee-cookie-consent' ) "
										:data-test-id="`wcc-consent-logs-delete-button`"
									>
									<div> 
										<base-icon
										class=""
										icon="trash"
										height="14"
										color="#D63638"
										></base-icon>	<a @click="deleteLog" :data-test-id="`wcc-consent-logs-delete-button-link`">{{$i18n.__("Delete history", "webtoffee-cookie-consent")}} </a>
									</div>
									</base-popper>
								</li>
							</ul>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="wcc-section-content">
			<div class="wcc-consent-logs-table">
				<consent-logs-table
					tableClass="wcc-table-stripped"
					@consentLogLoaded="consentLoaded"
				/>
			</div>
		</div>
	</div>
</template>

<script>
import ConsentLogsTable from "@/modules/consentlogs/components/consent-logs-table.vue";
import wccRest from "@/helpers/api";
import BaseIcon from "@/components/icons/BaseIcon.vue";

export default {
	name: "ConsentLogs",
	components: {
		ConsentLogsTable,
		BaseIcon
	},
	data() {
		return {
			isConsentEmpty: true,
			showActionsMenu: false,
		};
	},
	computed: {
		/**
		 * Computed method to access consent log settings.
		 *
		 * @since 3.0.0
		 *
		 * @returns {boolean}
		 */
		consentLog: {
			get() {
				return this.getOption("consent_logs").status;
			},
			set(value) {
				let data = {};
				data.status = value;
				this.setOption("consent_logs", data);
				this.saveOptions();
			},
		},
	},
	methods: {
		async exportLog() {
			this.$refs.wccButtonExportConsentLog.startLoading();
			try {
				const response = await wccRest.post({
					path: "consent_logs/export",
				});
				if (response.csv_url) {
					const link = document.createElement("a");
					link.href = response.csv_url;
					link.setAttribute("download", response.file_name);
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				} else {
					console.error("Export failed:", response.error || "Unknown error");
				}
			} catch (error) {
				console.error(error);
			}
			this.$refs.wccButtonExportConsentLog.stopLoading();
		},
		async deleteLog() {
			// Show confirmation alert before deleting
			const confirmMessage = this.$i18n.__(
				"Are you sure you want to delete all consent history? This action cannot be undone.",
				"webtoffee-cookie-consent"
			);
			
			if (!confirm(confirmMessage)) {
				return; // User cancelled, do nothing
			}
			
			try {
				const response = await wccRest.post({
					path: "consent_logs/delete",
				});
				if (response) {
					this.showSuccessMessage(this.$i18n.__("Consent logs deleted successfully!", "webtoffee-cookie-consent"));
					// Set a timeout to refresh the page after the success message is displayed
					setTimeout(() => {
						location.reload();
					}, 2000); // Adjust the timeout duration as needed
				} else {
					console.error("Deletion failed:", response.error || "Unknown error");
					this.showErrorMessage(this.$i18n.__("Failed to delete consent logs", "webtoffee-cookie-consent"));
				}
			} catch (error) {
				console.error(error);
			}
		},
		showSuccessMessage(message) {
			this.$root.$emit("triggerNotification", {
				type: "success",
				message: message,
			});
		},
		showErrorMessage(message) {
			this.$root.$emit("triggerNotification", {
				type: "error",
				message: message,
			});
		},
		consentLoaded(consents) {
			if(consents.length) this.isConsentEmpty = false;
		},
		toggleActionsMenu() {
			this.showActionsMenu = !this.showActionsMenu;
		},
	},
	mounted() {
		// Close menu when clicking outside
		document.addEventListener('click', (event) => {
			if (this.showActionsMenu && !event.target.closest('.wcc-consent-logs-more-actions')) {
				this.showActionsMenu = false;
			}
		});
	},
};
</script>
<style lang="scss" scoped>
.wcc-dropdown .wcc-button-no-style {
	display: flex;
}
.wcc-btn-consent-status {
	margin-left: 5px;
}

.wcc-toggle {
	margin-left: 10px;
}
.wcc-consent-logs-table {
	margin-top: calc($wcc-gutter/2);
}
.wcc-consent-logs-more-actions {
	position: relative;
	display: inline-block;
	margin-left: 14px;
	.wcc-button {
		font-size: 24px;
	}
}
.wcc-consent-logs-more-actions-list {
	position: absolute;
	background-color: #fafafb;
	width: max-content;
	border-radius: 3px;
	min-width: 130px;
	z-index: 1;
	right: 0;
	top:40px;
	.wcc-popper-container,
		.wcc-poppper-trigger {
			.wcc-popper {
				width: 150px;
			}
		}
	.wcc-popper-container {
		border-radius: 6px;
		box-shadow: 0px 3px 10px 0px #798DA04D;
		width: 150px;
		
	}
	ul {
		list-style: none;
		padding-left: 0;
		margin: 0;
		li {
			margin-bottom: 0px;
			display: flex;
			flex-direction: column;
			a {
				display: flex;
				color:#D63638;
			}
		}
	}
}
.wcc-consent-logs-more-actions-list ul li .wcc-popper-container .wcc-poppper-trigger div{
	display:inline-flex !important;
	align-items: center;
	justify-content: center;
	padding-left: 14px;
}
.wcc-consent-logs-more-actions-list a {
	color: #3c434a;
	padding: 10px;
	text-decoration: none;
	display: block;
}
.wcc-consent-logs-more-actions-list a:hover {
	cursor: pointer;
}
</style>