import { Modal } from 'bootstrap';

document.addEventListener('DOMContentLoaded', function () {
	const createMembershipSaleButton = document.getElementById('btn-user-membership-sale');
	const formatCurrency = (amount) => {
		const numericAmount = Number(amount ?? 0);
		const safeAmount = Number.isFinite(numericAmount) ? numericAmount : 0;

		return safeAmount.toLocaleString('es-VE', {
			minimumFractionDigits: 2,
			maximumFractionDigits: 2,
		});
	};

	const escapeHtml = (value) => {
		return String(value ?? '')
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	};

	if (createMembershipSaleButton) {
		createMembershipSaleButton.addEventListener('click', async function () {
			const previewUrl = this.getAttribute('data-preview-url') || '';
			const createUrl = this.getAttribute('data-create-url') || '';
			const userName = this.getAttribute('data-user-name') || 'Cliente';
			const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

			if (!previewUrl || !createUrl) {
				return;
			}

			this.disabled = true;

			try {
				const previewResponse = await fetch(previewUrl, {
					method: 'GET',
					headers: {
						Accept: 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
					},
				});

				const previewPayload = await previewResponse.json().catch(() => ({}));
				if (!previewResponse.ok || previewPayload.success === false) {
					throw new Error(previewPayload.message || 'No se pudo calcular el monto de la membresia.');
				}

				const preview = previewPayload.data || {};
				const membershipName = String(preview.membership_name || 'Membresia');
				const baseTotal = Number(preview.base_total ?? 0);
				const totalWithRate = Number(preview.total_with_rate ?? 0);
				const rate = Number(preview.amount_rate ?? 1);

				const result = await window.Swal.fire({
					title: 'Crear nuevo documento',
					html: `
						<div class="text-start">
							<p class="mb-1"><strong>Cliente:</strong> ${escapeHtml(userName)}</p>
							<p class="mb-1"><strong>Membresia:</strong> ${escapeHtml(membershipName)}</p>
							<p class="mb-1"><strong>Monto base:</strong> ${formatCurrency(baseTotal)}</p>
							<p class="mb-1"><strong>Tasa:</strong> ${formatCurrency(rate)}</p>
							<p class="mb-0"><strong>Monto a sumar:</strong> ${formatCurrency(totalWithRate)}</p>
						</div>
					`,
					icon: 'question',
					showCancelButton: true,
					confirmButtonText: 'Crear documento',
					cancelButtonText: 'Cancelar',
					reverseButtons: true,
				});

				if (!result.isConfirmed) {
					return;
				}

				const createResponse = await fetch(createUrl, {
					method: 'POST',
					headers: {
						Accept: 'application/json',
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
						'X-CSRF-TOKEN': csrfToken,
					},
					body: JSON.stringify({}),
				});

				const createPayload = await createResponse.json().catch(() => ({}));
				if (!createResponse.ok || createPayload.success === false) {
					throw new Error(createPayload.message || 'No se pudo crear el documento.');
				}

				await window.Swal.fire({
					title: 'Documento creado',
					text: `Se creo el documento #${createPayload?.data?.sale_identifier ?? ''} por ${createPayload?.data?.total_formatted ?? formatCurrency(totalWithRate)}.`,
					icon: 'success',
				});
			} catch (error) {
				await window.Swal.fire({
					title: 'No se pudo crear el documento',
					text: error?.message || 'Ocurrio un error creando el documento.',
					icon: 'error',
				});
			} finally {
				this.disabled = false;
			}
		});
	}

	const openSalesModalButton = document.getElementById('btn-user-sales-modal');
	const salesModalElement = document.getElementById('userSalesModal');
	const salesTable = $('#userSalesTable');
	const userSalesDebtTotal = document.getElementById('user-sales-debt-total');
	const userSalesAuxDebtTotal = document.getElementById('user-sales-aux-debt-total');

	if (!openSalesModalButton || !salesModalElement || !salesTable.length || !userSalesDebtTotal || !userSalesAuxDebtTotal) {
		return;
	}

	const salesModal = new Modal(salesModalElement);
	let salesDataTable = null;

	const formatAmount = (amount) => {
		return Number(amount ?? 0).toFixed(2);
	};

	const formatCurrencyVE = (amount) => {
		const numericAmount = Number(amount ?? 0);
		const safeAmount = Number.isFinite(numericAmount) ? numericAmount : 0;

		return safeAmount.toLocaleString('es-VE', {
			minimumFractionDigits: 2,
			maximumFractionDigits: 2,
		});
	};

	const flattenSales = (sales) => {
		const rows = [];

		sales.forEach((sale) => {
			const saleId = sale.id ?? null;
			const saleLabel = `#${sale.id} (${sale.status ?? 'sin estado'})`;
			const saleDate = sale.created_at_formatted ?? '-';
			const saleStatus = String(sale.status ?? '').trim().toLowerCase();

			const productRows = Array.isArray(sale.products) ? sale.products : [];
			productRows.forEach((item) => {
				rows.push({
					sale_id: saleId,
					sale_label: saleLabel,
					sale_date: saleDate,
					sale_total: sale.total ?? 0,
					sale_debt: sale.debt ?? 0,
					sale_aux_debt: sale.aux_debt ?? 0,
					sale_status: saleStatus,
					type: 'Producto',
					description: item.product_name ?? 'Producto sin nombre',
					quantity: item.quantity ?? 0,
					unit_price: item.unit_price ?? 0,
					subtotal: item.subtotal ?? 0,
				});
			});

			const membershipRows = Array.isArray(sale.memberships) ? sale.memberships : [];
			membershipRows.forEach((item) => {
				rows.push({
					sale_id: saleId,
					sale_label: saleLabel,
					sale_date: saleDate,
					sale_total: sale.total ?? 0,
					sale_debt: sale.debt ?? 0,
					sale_aux_debt: sale.aux_debt ?? 0,
					sale_status: saleStatus,
					type: 'Membresia',
					description: item.membership_name ?? 'Membresia sin nombre',
					quantity: item.quantity ?? 0,
					unit_price: item.unit_price ?? 0,
					subtotal: item.subtotal ?? 0,
				});
			});

			if (productRows.length === 0 && membershipRows.length === 0) {
				rows.push({
					sale_id: saleId,
					sale_label: saleLabel,
					sale_date: saleDate,
					sale_total: sale.total ?? 0,
					sale_debt: sale.debt ?? 0,
					sale_aux_debt: sale.aux_debt ?? 0,
					sale_status: saleStatus,
					type: '-',
					description: 'Venta sin detalles registrados',
					quantity: '-',
					unit_price: '-',
					subtotal: sale.total ?? 0,
				});
			}
		});

		return rows;
	};

	const updateFilteredDebtTotal = () => {
		if (!salesDataTable) {
			userSalesDebtTotal.textContent = formatCurrencyVE(0);
			userSalesAuxDebtTotal.textContent = formatCurrencyVE(0);
			return;
		}

		const visibleRows = salesDataTable.rows({ search: 'applied' }).data().toArray();
		const processedSaleIds = new Set();
		let totalDebt = 0;
		let totalAuxDebt = 0;

		visibleRows.forEach((row) => {
			const rowSaleId = row?.sale_id;
			const saleKey = rowSaleId !== null && rowSaleId !== undefined ? String(rowSaleId) : null;
			const saleStatus = String(row?.sale_status ?? '').trim().toLowerCase();

			if (saleStatus === 'cancelada') {
				return;
			}

			if (saleKey) {
				if (processedSaleIds.has(saleKey)) {
					return;
				}

				processedSaleIds.add(saleKey);
			}

			totalDebt += Number(row?.sale_debt ?? 0);
			totalAuxDebt += Number(row?.sale_aux_debt ?? 0);
		});

		userSalesDebtTotal.textContent = formatCurrencyVE(totalDebt);
		userSalesAuxDebtTotal.textContent = formatCurrencyVE(totalAuxDebt);
	};

	const buildDataTable = (salesUrl) => {
		salesDataTable = salesTable.DataTable({
			processing: true,
			serverSide: false,
			searching: true,
			ordering: true,
			paging: true,
			pageLength: 10,
			lengthMenu: [10, 15, 30],
			autoWidth: false,
			ajax: {
				url: salesUrl,
				type: 'GET',
				dataSrc: function (json) {
					const sales = Array.isArray(json?.data) ? json.data : [];
					return flattenSales(sales);
				},
				error: function () {
					salesTable.closest('.dataTables_wrapper').find('.dataTables_empty').text('No se pudo cargar el historial de ventas.');
				},
			},
			columns: [
				{ data: 'sale_label', name: 'sale_label' },
				{ data: 'sale_date', name: 'sale_date' },
				{
					data: 'sale_total',
					name: 'sale_total',
					className: 'text-end',
					render: function (data) {
						return `${formatAmount(data)}`;
					},
				},
				{
					data: 'sale_debt',
					name: 'sale_debt',
					className: 'text-end',
					render: function (data) {
						return `${formatAmount(data)}`;
					},
				},
				{ data: 'type', name: 'type' },
				{ data: 'description', name: 'description' },
				{
					data: 'quantity',
					name: 'quantity',
					className: 'text-end',
					render: function (data) {
						if (data === '-') {
							return '-';
						}
						return Number(data ?? 0).toFixed(2);
					},
				},
				{
					data: 'unit_price',
					name: 'unit_price',
					className: 'text-end',
					render: function (data) {
						if (data === '-') {
							return '-';
						}
						return `${formatAmount(data)}`;
					},
				},
				{
					data: 'subtotal',
					name: 'subtotal',
					className: 'text-end',
					render: function (data) {
						return `${formatAmount(data)}`;
					},
				},
			],
			createdRow: function (row, data) {
				if (data?.sale_status == 'completada') {
					$(row).addClass('text-success');
				}
			},
			order: [[1, 'desc']],
			language: {
				processing: 'Procesando...',
				search: 'Buscar:',
				lengthMenu: 'Mostrar _MENU_ registros',
				info: 'Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros',
				infoEmpty: 'Mostrando registros del 0 al 0 de un total de 0 registros',
				infoFiltered: '(filtrado de un total de _MAX_ registros)',
				loadingRecords: 'Cargando...',
				zeroRecords: 'No se encontraron resultados',
				emptyTable: 'Este usuario no tiene ventas registradas.',
				paginate: {
					first: 'Primero',
					previous: 'Anterior',
					next: 'Siguiente',
					last: 'Ultimo',
				},
				aria: {
					sortAscending: ': Activar para ordenar la columna de manera ascendente',
					sortDescending: ': Activar para ordenar la columna de manera descendente',
				},
			},
		});

		salesTable.on('draw.dt', function () {
			updateFilteredDebtTotal();
		});
	};

	openSalesModalButton.addEventListener('click', function () {
		const salesUrl = this.getAttribute('data-sales-url');

		if (!salesUrl) {
			return;
		}

		if (!salesDataTable) {
			buildDataTable(salesUrl);
		} else {
			salesDataTable.ajax.url(salesUrl).load();
		}

		salesModal.show();
	});

	salesModalElement.addEventListener('shown.bs.modal', function () {
		if (salesDataTable) {
			salesDataTable.columns.adjust();
		}
	});

	salesModalElement.addEventListener('hidden.bs.modal', function () {
		if (salesDataTable) {
			salesDataTable.search('').draw();
		}

		userSalesDebtTotal.textContent = formatCurrencyVE(0);
			userSalesAuxDebtTotal.textContent = formatCurrencyVE(0);
	});
});