import "../libs/flatpickr";
import { PIXELIOCARTABANDONRECOVERYMOREHIDEIT } from "../../../../frontend/assets/js/var/pixelio_cart_abandon_recovery_more_variable";
import {
	PixelioCartAbandonRecoveryMoreUpdate
} from "../components/pixelio_cart_abandon_recovery_more_update_popup";
jQuery(document).ready(function ($) {

	const apiKey = pixelio_ajax.apiKey;
	const noDataText = pixelio_ajax.noDataText;

	// Initialisation du datepicker
	$("#pixelio-cart-abandon-recovery-more-date-range").flatpickr({
		mode: "range",
		dateFormat: "Y-m-d",
		onClose: function (selectedDates, dateStr, instance) {
			// callback vide pour le moment
		}
	});

	// Gestion du select pour afficher/cacher le champ custom
	$("#pixelio-cart-abandon-recovery-more-select-date-dashboard").on('change', function () {
		var selectedValue = $(this).val();
		var $customInput = $("#pixelio-cart-abandon-recovery-more-date-range");

		if (selectedValue === 'custom') {
			$customInput.removeClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
			$customInput.prop('required', true);
		} else {
			$customInput.addClass(PIXELIOCARTABANDONRECOVERYMOREHIDEIT);
			$customInput.prop('required', false);
		}
	});


	function fetchData(url, onSuccess) {
		$.ajax({
			url: url,
			method: 'GET',
			dataType: 'json',
			headers: {
				'x-api-key': apiKey,
			},
			data: pixelio_ajax.isIa ? { isIa: true } : {},
			success: onSuccess,
			error: function (xhr, status, err) {
				console.error('Erreur chargement ' + url + ':', err);
			}
		});
	}

	function loadGlobalKPI() {
		fetchData(pixelio_ajax.kpiGlobalUrl, function (res) {
			if (res.success && res.kpi) {
				const d = res.kpi;
				const $kpi = $('.pixelio-cart-abandon-recovery-more-kpi-container .pixelio-cart-abandon-recovery-more-kpi');
				const values = [
					d.abandonmentRate,
					d.emailsSent,
					d.openRate,
					d.recoveryRate,
					d.avgRecoveredCart,
					d.revenueGenerated.toLocaleString()
				];
				values.forEach(function (val, i) {
					$kpi.eq(i).find('strong')
						.text(val)
						.removeClass('is-loading')
						.addClass('is-ready');

					$kpi.eq(i).find('.pixelio-kpi-helper').text('Updated from live store data');
					if (typeof val === 'string' && val.includes('*')) {
						jQuery(".pixelio-cart-abandon-recovery-more-analyze-explanation").removeClass("pixelio-cart-abandon-recovery-more-hide-it");
					}
				});
			} else {
				console.warn('Réponse invalide KPI global', res);
				jQuery(".pixelio-cart-abandon-recovery-more-analyze-explanation")
					.removeClass("pixelio-cart-abandon-recovery-more-hide-it");
			}
		});
	}

	function loadKPIByEmail() {
		fetchData(pixelio_ajax.kpiByEmailUrl, function (res) {
			if (res.success && res.emails) {
				const $tbody = $('#emails-table tbody').empty();
				$.each(res.emails, function (i, email) {
					$tbody.append(
						'<tr>' +
						'<td>' + (i + 1) + '</td>' +
						'<td>' + email.emailName + '</td>' +
						'<td>' + email.sent + '</td>' +
						'<td>' + email.opens + ' (' + (email.sent ? ((email.opens / email.sent) * 100).toFixed(1) : 0) + '%)</td>' +
						'<td>' + email.clicks + ' (' + (email.sent ? ((email.clicks / email.sent) * 100).toFixed(1) : 0) + '%)</td>' +
						'<td>' + email.conversions + ' (' + (email.sent ? ((email.conversions / email.sent) * 100).toFixed(1) : 0) + '%)</td>' +
						'<td>' + email.revenue + '</td>' +
						'</tr>'
					);
				});

				if ($.fn.DataTable.isDataTable('#emails-table')) $('#emails-table').DataTable().destroy();
				$('#emails-table').DataTable({
					lengthChange: false,
					info: false,
					searching: false,
					pageLength: 5,
					paging: false,
					responsive: true,
					order: [[1, 'desc']],
					language: { emptyTable: noDataText }
				});
			} else {
				console.warn('Réponse invalide KPI par email', res);
			}
		});
	}

	function loadProductsKPI() {
		fetchData(pixelio_ajax.kpiByProductUrl, function (res) {
			if (res.products) {
				const $tbody = $('#products-table tbody').empty();
				$.each(res.products, function (i, p) {
					$tbody.append(
						'<tr>' +
						'<td>' + p.productName + '</td>' +
						'<td>' + p.abandonedCarts + '</td>' +
						'<td>' + p.totalValue + '</td>' +
						'<td>' + p.lastAbandon + '</td>' +
						'</tr>'
					);
				});

				if ($.fn.DataTable.isDataTable('#products-table')) $('#products-table').DataTable().destroy();
				$('#products-table').DataTable({
					lengthChange: false,
					info: false,
					searching: false,
					paging: false,
					pageLength: 5,
					responsive: true,
					order: [[1, 'desc']],
					language: { emptyTable: noDataText }
				});
			} else {
				console.warn('Réponse invalide KPI produits', res);
			}
		});
	}

	function loadAbandonedCarts() {
		const STATUS_MAP = {
			empty: {
				en: 'Empty',
				fr: 'Panier Vide',
			},
			active: {
				en: 'Active',
				fr: 'Actif',
			},
			pending: {
				en: 'Pending',
				fr: 'En attente',
			},
			completed: {
				en: 'Completed',
				fr: 'Terminé',
			},
			processing: {
				en: 'Processing',
				fr: 'En cours',
			},
			on_hold: {
				en: 'On hold',
				fr: 'En attente',
			},
			canceled: {
				en: 'Canceled',
				fr: 'Annulé',
			},
			failed: {
				en: 'Failed',
				fr: 'Échoué',
			},
			refunded: {
				en: 'Refunded',
				fr: 'Remboursé',
			},
			returned: {
				en: 'Returned',
				fr: 'Retourné',
			},
			abandoned: {
				en: 'Abandoned',
				fr: 'Abandonné',
			},
			completely_abandoned: {
				en: 'Completely Abandoned',
				fr: 'Complètement abandonné',
			},
			recovered: {
				en: 'Recovered',
				fr: 'Récupéré',
			},
			recovered_and_purchased: {
				en: 'Recovered and Purchased',
				fr: 'Récupéré et acheté',
			},
			review_gived_with_recover: {
				en: 'Review given with recovery',
				fr: 'Avis donné avec récupération',
			},
			review_gived_without_recover: {
				en: 'Review given without recovery',
				fr: 'Avis donné sans récupération',
			},
		};
		function translateStatus(statusName) {
			const langs = pixelio_ajax.lang;
			const firstLang = langs[0].slice(0, 2)
			if (!statusName) return 'Inconnu';
			const status = STATUS_MAP[statusName];
			if (!status) return 'Inconnu';
			return status[firstLang] || status['en'];
		}
		fetchData(pixelio_ajax.kpiAbandonedCartsUrl, function (res) {
			if (res.abandonedCarts) {
				const $tbody = $('#logs-table tbody').empty();
				$.each(res.abandonedCarts, function (i, c) {
					$tbody.append(
						'<tr>' +
						'<td>' + c.cartId + '</td>' +
						'<td>' + c.value + '</td>' +
						'<td>' + c.date + '</td>' +
						'<td>' + translateStatus(c.status) + '</td>' +
						'</tr>'
					);
				});

				if ($.fn.DataTable.isDataTable('#logs-table')) $('#logs-table').DataTable().destroy();
				$('#logs-table').DataTable({
					lengthChange: false,
					info: false,
					searching: false,
					paging: false,
					pageLength: 10,
					responsive: true,
					order: [[3, 'desc']],
					language: { emptyTable: noDataText }
				});
			} else {
				console.warn('Réponse invalide KPI paniers', res);
			}
		});
	}

	// Chargement des données
	loadGlobalKPI();
	loadKPIByEmail();
	loadProductsKPI();
	loadAbandonedCarts();

});
