$(document).ready(function () {
	// Initial setup
	loadReportTypes();

	$('#aiResponseContent').hide();
	$('#demoResponse').show();

	// PDF download
	$('#downloadPdfBtn').off('click').on('click', function () {
		const original = document.getElementById('pdfContent');
		const clone = original.cloneNode(true);
		clone.style.maxWidth = '700px';
		clone.style.margin = 'auto';
		clone.style.padding = '20px';
		clone.style.background = 'white';

		const originalCanvas = document.getElementById('summaryChart');
		if (originalCanvas) {
			const imageData = originalCanvas.toDataURL('image/png');
			const clonedCanvas = clone.querySelector('#summaryChart');
			if (clonedCanvas) {
				clonedCanvas.parentNode.removeChild(clonedCanvas);
				const img = document.createElement('img');
				img.src = imageData;
				img.style.width = '600px';
				img.style.height = '400px';
				img.style.display = 'block';
				img.style.margin = '20px auto';
				const parent = clone.querySelector('#aiResponseBox') || clone;
				parent.appendChild(img);
			}
		}

		clone.classList.add('print-pdf');
		const container = document.createElement('div');
		container.style.position = 'fixed';
		container.style.left = '-9999px';
		container.appendChild(clone);
		document.body.appendChild(container);

		const opt = {
			margin: 0.5,
			filename: 'AI_Business_Analysis_' + new Date().toISOString().slice(0, 10) + '.pdf',
			image: { type: 'jpeg', quality: 0.98 },
			html2canvas: { scale: 1, useCORS: true },
			jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' },
			pagebreak: { mode: ['avoid-all', 'css', 'legacy'], before: '#summaryChart' }
		};

		html2pdf().set(opt).from(clone).save().then(() => {
			document.body.removeChild(container);
		});
	});

	// AI chat submit
	$('#aiChatForm').off('submit').on('submit', function (e) {
		e.preventDefault();
		$.ajax({
			url: BASE_URL + 'dashboard/AI_Controller/bdtask_get_ai_analysis',
			method: 'POST',
			data: $(this).serialize(),
			dataType: 'json',
			beforeSend: function () {
				$('#aiResponseContent').html('<i>Generating AI response...</i>').show();
				$('#demoResponse').hide();
				$('#downloadBtnWrap').hide();
			},
			success: function (res) {
				if (window.summaryChart instanceof Chart) {
					window.summaryChart.destroy();
				}
				$('#summaryChart').hide();
				$('#aiResponseContent').html('');

				if (res.status === 'success') {
					let aiText = res.response.trim();

					if (aiText.includes('Insights:')) {
						const [jsonPartRaw, ...insightParts] = aiText.split('Insights:');
						const insightsText = insightParts.join('Insights:').trim();

						try {
							const chartJson = JSON.parse(jsonPartRaw.trim());
							$('#aiResponseContent').html(`<div class="insights-text">${insightsText.replace(/\n/g, '<br>')}</div>`);
							renderChart(chartJson);
							$('#summaryChart').show();
							$('#downloadBtnWrap').show();
							return;
						} catch (err) {
							console.error('Chart JSON parse failed', err);
							if (insightsText) {
								$('#aiResponseContent').html(`<div class="insights-text">${insightsText.replace(/\n/g, '<br>')}</div>`);
								$('#downloadBtnWrap').show();
								return;
							}
						}
					}

					try {
						const possibleJson = JSON.parse(aiText);
						if (possibleJson.headers && possibleJson.rows) {
							renderHtmlTable(possibleJson.headers, possibleJson.rows);
							$('#downloadBtnWrap').show();
							return;
						}
					} catch (e) { }

					if (aiText.includes('|') && aiText.includes('---')) {
						let htmlFromMd = markdownTableToHtml(aiText);
						$('#aiResponseContent').html(htmlFromMd);
						$('#downloadBtnWrap').show();
						return;
					}

					$('#aiResponseContent').html(`<div class="insights-text">${aiText.replace(/\n/g, '<br>')}</div>`);
					$('#downloadBtnWrap').show();

					if (res.chart_data && res.chart_data.labels && res.chart_data.labels.length > 0) {
						renderChart(res.chart_data);
						$('#summaryChart').show();
					}
				} else {
					$('#aiResponseContent').html('<span class="text-danger">Error: ' + res.message + '</span>');
					$('#demoResponse').show();
					$('#downloadBtnWrap').hide();
				}
			},
			error: function () {
				$('#aiResponseContent').html('<span class="text-danger">Something went wrong.</span>');
				$('#demoResponse').show();
				$('#downloadBtnWrap').hide();
			}
		});
	});

	// Add type modal
	$('.btn_add_new_type').on('click', function () {
		$('#addReportTypeModal').addClass('show');
	});
	$('#closeModalBtn').on('click', function () {
		$('#addReportTypeModal').removeClass('show');
	});
	$('#addReportTypeModal').on('click', function (e) {
		if ($(e.target).hasClass('modal_overlay')) {
			$(this).removeClass('show');
		}
	});
	$('#saveReportType').click(function () {
		const name = $('#new_report_type').val().trim();
		if (name) {
			$.post(BASE_URL + 'dashboard/AI_Controller/add_report_type', { name: name }, function (response) {
				const res = JSON.parse(response);
				if (res.status === 'success') {
					$('#new_report_type').val('');
					$('#addReportTypeModal').removeClass('show');
					loadReportTypes();
				} else {
					alert(res.message || 'Failed to add type');
				}
			});
		}
	});

	// Remove type modal
	$('.btn_remove_type').on('click', function () {
		loadRemoveTypeList();
		$('#removeReportTypeModal').addClass('show');
	});
	$('#closeRemoveModalBtn').on('click', function () {
		$('#removeReportTypeModal').removeClass('show');
	});
	$('#removeReportTypeModal').on('click', function (e) {
		if ($(e.target).hasClass('modal_overlay')) {
			$(this).removeClass('show');
		}
	});
	$('#removeTypeList').on('click', '.btn_delete_type', function () {
		const name = $(this).data('name');
		$.post(BASE_URL + 'dashboard/AI_Controller/delete_report_type', { name: name }, function (response) {
			const res = JSON.parse(response);
			if (res.status === 'success') {
				loadReportTypes();
				loadRemoveTypeList();
			} else {
				alert(res.message || 'Delete failed!');
			}
		});
	});

	// Select dropdown badge remove
	$('#report_type').on('change', function () {
		const selected = $(this).val();
		const container = $('#selectedItemsContainer');
		container.empty();
		if (selected && selected.length > 0) {
			selected.forEach(function (item) {
				container.append(`<span class="selected_item" data-value="${item}">${item} <span class="remove_item">&times;</span></span>`);
			});
		}
	});
	$('#selectedItemsContainer').on('click', '.remove_item', function () {
		const badge = $(this).closest('.selected_item');
		const value = badge.data('value').toString();
		const select = $('#report_type');
		const updated = (select.val() || []).filter(v => v !== value);
		select.val(updated).trigger('change');
	});

	// Date picker setup
	const $input = $('input[name="daterange"]');
	$input.daterangepicker({
		autoUpdateInput: false,
		locale: { cancelLabel: 'Clear' },
		opens: 'left'
	}, function (start, end) {
		$input.val(start.format('MM/DD/YYYY') + ' - ' + end.format('MM/DD/YYYY'));
		$('#date_from').val(start.format('YYYY-MM-DD'));
		$('#date_to').val(end.format('YYYY-MM-DD'));
	});
	$input.on('cancel.daterangepicker', function () {
		$(this).val('');
	});
	$('.calender_icon').on('click', function () {
		$input.trigger('click');
	});

	let instructionsVisible = false;
  let exampleVisible = false;

  $('#toggleInstructions').off('click').on('click', function(e) {
    e.preventDefault();
    instructionsVisible = !instructionsVisible;
    $('#instructionsBox').stop(true, true).slideToggle();
    if (exampleVisible) {
      exampleVisible = false;
      $('#exampleBox').stop(true, true).slideUp();
    }
  });

  $('#toggleExample').off('click').on('click', function(e) {
    e.preventDefault();
    exampleVisible = !exampleVisible;
    $('#exampleBox').stop(true, true).slideToggle();
    if (instructionsVisible) {
      instructionsVisible = false;
      $('#instructionsBox').stop(true, true).slideUp();
    }
  });

  $('#copyExampleBtn').off('click').on('click', function() {
    const exampleText = document.getElementById('examplePromptText').innerText.trim();
    const textarea = document.querySelector('textarea[name="user_input"]');
    textarea.value = exampleText;
    textarea.focus();
  });
});

// Utility functions
function loadReportTypes() {
	$.getJSON(BASE_URL + 'dashboard/AI_Controller/get_report_types', function (data) {
		const container = $('#report_type').empty();
		data.forEach(item => container.append(`<option value="${item.name}">${item.name}</option>`));
	});
}

function loadRemoveTypeList() {
	$.getJSON(BASE_URL + 'dashboard/AI_Controller/get_report_types', function (data) {
		const container = $('#removeTypeList').empty();
		if (data.length === 0) {
			container.append('<p style="text-align:center;color:#888;">No report types found</p>');
		} else {
			data.forEach(item => {
				container.append(`<div class="report_type_item" style="display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid #eee;"><span>${item.name}</span><button class="btn_delete_type" data-name="${item.name}" style="color:red;cursor:pointer;border:none;background:none;font-size:16px;">&#10005;</button></div>`);
			});
		}
	});
}

function markdownTableToHtml(mdText) {
	const lines = mdText.trim().split('\n');
	let html = '<h5>📋 AI Table Analysis</h5><table class="table table-bordered">';
	const headerLine = lines.find(line => line.includes('|') && !line.includes('---'));
	if (!headerLine) return '<pre>' + mdText + '</pre>';
	const headers = headerLine.split('|').map(h => h.trim()).filter(Boolean);
	html += '<thead><tr>' + headers.map(h => `<th>${h}</th>`).join('') + '</tr></thead><tbody>';
	let dataStarted = false;
	for (let line of lines) {
		if (line.includes('---')) {
			dataStarted = true;
			continue;
		}
		if (!dataStarted || !line.includes('|')) continue;
		const cells = line.split('|').map(c => c.trim()).filter(Boolean);
		if (cells.length > 0) {
			html += '<tr>' + cells.map(c => `<td>${c}</td>`).join('') + '</tr>';
		}
	}
	html += '</tbody></table>';
	return html;
}

function renderChart(chartData) {
	const ctx = document.getElementById('summaryChart').getContext('2d');
	if (window.summaryChart instanceof Chart) window.summaryChart.destroy();
	window.summaryChart = new Chart(ctx, {
		type: 'line',
		data: {
			labels: chartData.labels,
			datasets: [
				{ label: 'Sales', data: chartData.sales, borderColor: 'green', backgroundColor: 'rgba(0,128,0,0.1)', fill: true, tension: 0.3 },
				{ label: 'Purchases', data: chartData.purchases, borderColor: 'orange', backgroundColor: 'rgba(255,165,0,0.1)', fill: true, tension: 0.3 },
				{ label: 'Stock', data: chartData.stock, borderColor: 'blue', backgroundColor: 'rgba(2, 53, 223, 0.87)', fill: true, tension: 0.3 },
				{ label: 'Sales Return', data: chartData.sales_return, borderColor: 'red', backgroundColor: 'rgba(255,0,0,0.3)', fill: true, tension: 0.3 },
				{ label: 'Supplier Return', data: chartData.supplier_return, borderColor: 'purple', backgroundColor: 'rgba(128,0,128,0.3)', fill: true, tension: 0.3 }
			]
		},
		options: {
			responsive: true,
			plugins: {
				title: { display: true, text: 'Sales vs Purchase vs Stock Summary' }
			}
		}
	});
}
