<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<section class="panel">
	<div class="actions" style="justify-content:space-between; margin-top:0; margin-bottom:18px; gap:12px;">
		<a class="btn btn-outline" href="<?php echo site_url('inicio'); ?>">Regresar</a>
		<div class="actions" style="margin-top:0;">
			<a class="btn btn-outline" href="<?php echo site_url('tareas?status=open'); ?>">Abiertas</a>
			<a class="btn btn-outline" href="<?php echo site_url('tareas?status=completed'); ?>">Completadas</a>
		</div>
	</div>

	<h2 style="margin-bottom:8px;">Tareas</h2>
	<p style="margin-bottom:18px;">Aqui puedes revisar tus tareas asignadas, dejar una nota y terminarlas cuando las completes.</p>

	<?php if (!empty($flash_message)) { ?>
		<div style="margin-bottom:14px; padding:12px 14px; border-radius:16px; background:#e8f6ed; color:#1f6a35; font-weight:700;">
			<?php echo htmlspecialchars($flash_message, ENT_QUOTES, 'UTF-8'); ?>
		</div>
	<?php } ?>

	<?php if (!empty($flash_error)) { ?>
		<div style="margin-bottom:14px; padding:12px 14px; border-radius:16px; background:#fdecec; color:#8a1f1f; font-weight:700;">
			<?php echo htmlspecialchars($flash_error, ENT_QUOTES, 'UTF-8'); ?>
		</div>
	<?php } ?>

	<?php if (empty($assignments)) { ?>
		<div class="empty">No tienes tareas en esta vista.</div>
	<?php } else { ?>
		<div style="display:grid; gap:14px;">
			<?php foreach ($assignments as $assignment) { ?>
				<?php
				$status = isset($assignment['status']) ? $assignment['status'] : 'pending';
				$status_label = $status === 'completed' ? 'Completada' : ($status === 'overdue' ? 'Vencida' : ($status === 'in_progress' ? 'En progreso' : 'Pendiente'));
				$items_payload = array();
				foreach ((array) $assignment['items'] as $item)
				{
					$items_payload[] = array(
						'id' => isset($item['id']) ? (int) $item['id'] : 0,
						'name' => isset($item['name']) ? $item['name'] : '',
						'status' => isset($item['status']) ? $item['status'] : 'pending',
					);
				}
				$notes_payload = array();
				foreach ((array) $assignment['notes'] as $note_row)
				{
					$notes_payload[] = array(
						'note_type' => isset($note_row['note_type']) ? $note_row['note_type'] : 'manual',
						'note_text' => isset($note_row['note_text']) ? $note_row['note_text'] : '',
						'created_at' => isset($note_row['created_at']) ? $note_row['created_at'] : '',
					);
				}
				?>
				<div class="task-card" data-assignment-id="<?php echo (int) $assignment['id']; ?>" style="padding:16px 18px; border-radius:22px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:12px;">
					<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px;">
						<div style="display:grid; gap:6px;">
							<div style="font-size:calc(1.02rem * var(--app-text-size)); font-weight:800; color:var(--ink);">
								<?php echo htmlspecialchars($assignment['title'], ENT_QUOTES, 'UTF-8'); ?>
							</div>
							<div style="font-size:calc(0.88rem * var(--app-text-size)); color:var(--muted);">
								Asignada: <?php echo htmlspecialchars(date('d/m/Y', strtotime($assignment['assigned_date'])), ENT_QUOTES, 'UTF-8'); ?>
							</div>
						</div>
						<div class="task-status-badge" style="padding:8px 12px; border-radius:999px; background:<?php echo $status === 'completed' ? '#e8f6ed' : ($status === 'overdue' ? '#fdecec' : '#edf3ff'); ?>; color:<?php echo $status === 'completed' ? '#1f6a35' : ($status === 'overdue' ? '#8a1f1f' : '#355ca8'); ?>; font-weight:800; font-size:calc(0.82rem * var(--app-text-size));">
							<?php echo htmlspecialchars($status_label, ENT_QUOTES, 'UTF-8'); ?>
						</div>
					</div>

					<?php if (!empty($assignment['description'])) { ?>
						<div style="font-size:calc(0.92rem * var(--app-text-size)); color:var(--muted);">
							<?php echo nl2br(htmlspecialchars($assignment['description'], ENT_QUOTES, 'UTF-8')); ?>
						</div>
					<?php } ?>

					<?php if (!empty($assignment['items'])) { ?>
						<div style="display:grid; gap:8px; padding:14px; border-radius:18px; background:var(--card);">
							<div class="task-progress-text" style="font-size:calc(0.85rem * var(--app-text-size)); color:var(--muted); font-weight:700;">
								<?php echo (int) $assignment['items_completed']; ?>/<?php echo (int) $assignment['items_total']; ?> subtareas completadas
							</div>
							<?php foreach ($assignment['items'] as $item) { ?>
								<div style="display:flex; align-items:center; gap:10px; color:<?php echo isset($item['status']) && $item['status'] === 'completed' ? 'var(--muted)' : 'var(--ink)'; ?>;">
									<span style="width:10px; height:10px; border-radius:999px; background:<?php echo isset($item['status']) && $item['status'] === 'completed' ? '#98a5b3' : 'var(--theme)'; ?>; display:inline-block;"></span>
									<span><?php echo htmlspecialchars($item['name'], ENT_QUOTES, 'UTF-8'); ?></span>
								</div>
							<?php } ?>
						</div>
					<?php } ?>

					<?php if (!empty($assignment['notes'])) { ?>
						<div style="display:grid; gap:8px; padding:14px; border-radius:18px; background:var(--card);">
							<div style="font-size:calc(0.85rem * var(--app-text-size)); color:var(--muted); font-weight:700;">Notas recientes</div>
							<?php foreach (array_slice($assignment['notes'], 0, 2) as $note_row) { ?>
								<div style="font-size:calc(0.88rem * var(--app-text-size)); color:var(--ink);">
									<?php echo htmlspecialchars($note_row['note_text'], ENT_QUOTES, 'UTF-8'); ?>
								</div>
							<?php } ?>
						</div>
					<?php } ?>

					<div class="actions" style="justify-content:flex-end; margin-top:0;">
						<?php if ($status !== 'completed') { ?>
							<button
								class="btn js-open-task-modal"
								type="button"
								data-assignment-id="<?php echo (int) $assignment['id']; ?>"
								data-title="<?php echo htmlspecialchars($assignment['title'], ENT_QUOTES, 'UTF-8'); ?>"
								data-note-required="<?php echo !empty($assignment['requires_note_on_complete']) ? '1' : '0'; ?>"
								data-items="<?php echo htmlspecialchars(json_encode($items_payload), ENT_QUOTES, 'UTF-8'); ?>"
								data-notes="<?php echo htmlspecialchars(json_encode($notes_payload), ENT_QUOTES, 'UTF-8'); ?>"
							>Terminar</button>
						<?php } else { ?>
							<div style="font-size:calc(0.88rem * var(--app-text-size)); color:var(--muted); font-weight:700;">
								Finalizada el <?php echo !empty($assignment['completed_at']) ? htmlspecialchars(date('d/m/Y h:i A', strtotime($assignment['completed_at'])), ENT_QUOTES, 'UTF-8') : 'N/D'; ?>
							</div>
						<?php } ?>
					</div>
				</div>
			<?php } ?>
		</div>
	<?php } ?>
</section>

<style>
.task-checklist-row {
	display: flex !important;
	flex-direction: row !important;
	align-items: center !important;
	gap: 14px;
	padding: 12px 14px;
	border-radius: 18px;
	background: rgba(255, 255, 255, 0.72);
	border: 1px solid rgba(77, 116, 195, 0.12);
	width: 100%;
	box-sizing: border-box;
}

.task-checklist-row.is-completed {
	background: rgba(77, 116, 195, 0.08);
}

.task-checklist-box {
	position: relative;
	width: 28px;
	height: 28px;
	flex: 0 0 28px;
	display: inline-flex;
	align-items: center;
	justify-content: center;
}

.task-checklist-box input {
	position: absolute;
	inset: 0;
	opacity: 0;
	margin: 0;
	cursor: pointer;
}

.task-checklist-mark {
	width: 28px;
	height: 28px;
	border-radius: 10px;
	border: 2px solid rgba(77, 116, 195, 0.35);
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: inset 0 1px 2px rgba(20, 41, 64, 0.08);
	transition: all 0.18s ease;
}

.task-checklist-mark::after {
	content: '';
	width: 8px;
	height: 14px;
	border-right: 3px solid transparent;
	border-bottom: 3px solid transparent;
	transform: rotate(45deg) translate(-1px, -1px);
	transition: all 0.18s ease;
}

.task-checklist-box input:checked + .task-checklist-mark {
	background: var(--theme);
	border-color: var(--theme);
	box-shadow: 0 10px 18px rgba(77, 116, 195, 0.22);
}

.task-checklist-box input:checked + .task-checklist-mark::after {
	border-right-color: #fff;
	border-bottom-color: #fff;
}

.task-checklist-label {
	display: flex !important;
	align-items: center !important;
	font-size: calc(0.98rem * var(--app-text-size));
	font-weight: 800;
	color: var(--ink);
	line-height: 1.2;
	text-align: left;
	min-height: 28px;
}

.task-checklist-content {
	display: flex !important;
	align-items: center !important;
	flex: 1 1 auto;
	min-width: 0;
	min-height: 28px;
}

.task-checklist-row.is-completed .task-checklist-label {
	color: var(--muted);
	text-decoration: line-through;
}
</style>

<div class="modal-backdrop" id="task-completion-modal">
	<div class="modal-card" style="width:min(100%, 520px);">
		<form method="post" action="<?php echo current_url().(!empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : ''); ?>" id="task-completion-form" style="display:grid; gap:16px;">
			<input type="hidden" name="assignment_id" id="task-completion-assignment-id" value="" />
			<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px;">
				<div>
					<h2 id="task-completion-title" style="margin-bottom:6px;">Terminar tarea</h2>
					<p style="margin:0;">Puedes dejar una nota antes de cerrar esta tarea.</p>
				</div>
				<button class="btn btn-outline" type="button" id="task-completion-close">Cerrar</button>
			</div>

			<div class="field" style="margin-top:0;">
				<label>Checklist</label>
				<div id="completion-items-list" style="display:grid; gap:10px; padding:14px; border-radius:18px; background:var(--card);"></div>
			</div>

			<div class="field" style="margin-top:0;">
				<label>Historial de notas</label>
				<div id="completion-notes-list" style="display:grid; gap:10px; padding:14px; border-radius:18px; background:var(--card);"></div>
			</div>

			<div class="field" style="margin-top:0;">
				<label for="completion_note">Nota</label>
				<textarea id="completion_note" name="completion_note" placeholder="Escribe algun comentario sobre la tarea"></textarea>
				<div id="completion-note-hint" style="margin-top:6px; font-size:calc(0.85rem * var(--app-text-size)); color:var(--muted);"></div>
			</div>

			<input type="hidden" name="action_type" id="task-action-type" value="complete" />
			<div class="actions" style="justify-content:flex-end; margin-top:0;">
				<button class="btn btn-outline" type="button" id="save-note-button">Guardar nota</button>
				<button class="btn" type="submit">Terminar</button>
			</div>
		</form>
	</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
	var modal = document.getElementById('task-completion-modal');
	var closeButton = document.getElementById('task-completion-close');
	var form = document.getElementById('task-completion-form');
	var assignmentInput = document.getElementById('task-completion-assignment-id');
	var titleNode = document.getElementById('task-completion-title');
	var noteInput = document.getElementById('completion_note');
	var noteHint = document.getElementById('completion-note-hint');
	var itemsList = document.getElementById('completion-items-list');
	var notesList = document.getElementById('completion-notes-list');
	var actionTypeInput = document.getElementById('task-action-type');
	var saveNoteButton = document.getElementById('save-note-button');
	var noteRequired = false;
	var updateItemUrl = <?php echo json_encode(site_url('tareas/item')); ?>;

	var getStatusPalette = function (status) {
		if (status === 'completed') {
			return { text: 'Completada', bg: '#e8f6ed', fg: '#1f6a35' };
		}
		if (status === 'overdue') {
			return { text: 'Vencida', bg: '#fdecec', fg: '#8a1f1f' };
		}
		if (status === 'in_progress') {
			return { text: 'En progreso', bg: '#edf3ff', fg: '#355ca8' };
		}
		return { text: 'Pendiente', bg: '#edf3ff', fg: '#355ca8' };
	};

	var escapeHtml = function (value) {
		return String(value || '')
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#39;');
	};

	var readButtonItems = function (assignmentId) {
		var button = document.querySelector('.js-open-task-modal[data-assignment-id="' + assignmentId + '"]');
		if (!button) {
			return [];
		}
		try {
			return JSON.parse(button.getAttribute('data-items') || '[]');
		} catch (error) {
			return [];
		}
	};

	var writeButtonItems = function (assignmentId, items) {
		var button = document.querySelector('.js-open-task-modal[data-assignment-id="' + assignmentId + '"]');
		if (!button) {
			return;
		}
		button.setAttribute('data-items', JSON.stringify(items || []));
	};

	var updateAssignmentCard = function (assignmentId, result) {
		var card = document.querySelector('.task-card[data-assignment-id="' + assignmentId + '"]');
		if (!card || !result) {
			return;
		}
		var progress = card.querySelector('.task-progress-text');
		if (progress && typeof result.items_completed !== 'undefined' && typeof result.items_total !== 'undefined') {
			progress.textContent = result.items_completed + '/' + result.items_total + ' subtareas completadas';
		}
		var badge = card.querySelector('.task-status-badge');
		if (badge && result.status) {
			var palette = getStatusPalette(result.status);
			badge.textContent = palette.text;
			badge.style.background = palette.bg;
			badge.style.color = palette.fg;
		}
	};

	var renderItems = function (assignmentId, items) {
		if (!itemsList) {
			return;
		}
		if (!items || !items.length) {
			itemsList.innerHTML = '<div style="font-size:calc(0.88rem * var(--app-text-size)); color:var(--muted);">Esta tarea no tiene subtareas.</div>';
			return;
		}
		itemsList.innerHTML = items.map(function (item) {
			var checked = item.status === 'completed' ? 'checked' : '';
			var completedClass = item.status === 'completed' ? ' is-completed' : '';
			return '<label class="task-checklist-row' + completedClass + '"><span class="task-checklist-box"><input class="js-completion-item" type="checkbox" data-assignment-id="' + assignmentId + '" data-item-id="' + item.id + '" ' + checked + ' /><span class="task-checklist-mark"></span></span><span class="task-checklist-content"><span class="task-checklist-label">' + escapeHtml(item.name) + '</span></span></label>';
		}).join('');
	};

	var renderNotes = function (notes) {
		if (!notesList) {
			return;
		}
		if (!notes || !notes.length) {
			notesList.innerHTML = '<div style="font-size:calc(0.88rem * var(--app-text-size)); color:var(--muted);">Todavia no hay notas para esta tarea.</div>';
			return;
		}
		notesList.innerHTML = notes.map(function (note) {
			var label = note.note_type === 'completion' ? 'Cierre' : 'Nota';
			return '<div style="display:grid; gap:4px;"><div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:700;">' + escapeHtml(label + (note.created_at ? ' · ' + note.created_at : '')) + '</div><div style="font-size:calc(0.9rem * var(--app-text-size)); color:var(--ink);">' + escapeHtml(note.note_text) + '</div></div>';
		}).join('');
	};

	var openModal = function (button) {
		if (!modal || !button) {
			return;
		}
		assignmentInput.value = button.getAttribute('data-assignment-id') || '';
		titleNode.textContent = button.getAttribute('data-title') || 'Terminar tarea';
		noteInput.value = '';
		noteRequired = button.getAttribute('data-note-required') === '1';
		noteHint.textContent = noteRequired ? 'Esta tarea requiere una nota para poder completarse.' : 'La nota es opcional.';
		actionTypeInput.value = 'complete';
		try {
			renderItems(assignmentInput.value, JSON.parse(button.getAttribute('data-items') || '[]'));
		} catch (error) {
			renderItems(assignmentInput.value, []);
		}
		try {
			renderNotes(JSON.parse(button.getAttribute('data-notes') || '[]'));
		} catch (error) {
			renderNotes([]);
		}
		modal.style.display = 'flex';
		noteInput.focus();
	};

	var closeModal = function () {
		if (modal) {
			modal.style.display = 'none';
		}
	};

	Array.prototype.slice.call(document.querySelectorAll('.js-open-task-modal')).forEach(function (button) {
		button.addEventListener('click', function () {
			openModal(button);
		});
	});

	if (closeButton) {
		closeButton.addEventListener('click', closeModal);
	}

	if (modal) {
		modal.addEventListener('click', function (event) {
			if (event.target === modal) {
				closeModal();
			}
		});
	}

	if (itemsList) {
		itemsList.addEventListener('change', function (event) {
			var checkbox = event.target;
			if (!checkbox.classList.contains('js-completion-item')) {
				return;
			}
			var payload = new URLSearchParams();
			payload.append('assignment_id', checkbox.getAttribute('data-assignment-id') || '');
			payload.append('assignment_item_id', checkbox.getAttribute('data-item-id') || '');
			payload.append('is_completed', checkbox.checked ? '1' : '0');

			fetch(updateItemUrl, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
					'X-Requested-With': 'XMLHttpRequest'
				},
				body: payload.toString()
			}).then(function (response) {
				return response.json();
			}).then(function (result) {
				if (!result || !result.success) {
					checkbox.checked = !checkbox.checked;
					alert(result && result.message ? result.message : 'No pudimos guardar el avance.');
					return;
				}
				var items = readButtonItems(payload.get('assignment_id'));
				items = items.map(function (item) {
					if (String(item.id) === String(payload.get('assignment_item_id'))) {
						item.status = checkbox.checked ? 'completed' : 'pending';
					}
					return item;
				});
				writeButtonItems(payload.get('assignment_id'), items);
				var row = checkbox.closest('.task-checklist-row');
				if (row) {
					row.classList.toggle('is-completed', checkbox.checked);
				}
				updateAssignmentCard(payload.get('assignment_id'), result);
			}).catch(function () {
				checkbox.checked = !checkbox.checked;
				alert('No pudimos guardar el avance de la subtarea.');
			});
		});
	}

	if (form) {
		form.addEventListener('submit', function (event) {
			if (actionTypeInput && actionTypeInput.value === 'add_note') {
				if (!noteInput.value.trim()) {
					event.preventDefault();
					alert('Escribe una nota antes de guardarla.');
					noteInput.focus();
				}
				return;
			}
			if (noteRequired && !noteInput.value.trim()) {
				event.preventDefault();
				alert('Esta tarea requiere una nota antes de terminarla.');
				noteInput.focus();
				return;
			}
			if (!window.confirm('¿Estas seguro de terminar esta tarea?')) {
				event.preventDefault();
			}
		});
	}

	if (saveNoteButton) {
		saveNoteButton.addEventListener('click', function () {
			if (actionTypeInput) {
				actionTypeInput.value = 'add_note';
			}
			form.requestSubmit();
		});
	}
});
</script>
