const Tasks = {
    page: 1,
    currentDetailId: null,

    async init() {
        this.bindEvents();
        await Promise.all([this.loadTasks(), this.loadUsers()]);
    },

    bindEvents() {
        $('#taskSearch').on('input', App.debounce(() => { this.page = 1; this.loadTasks(); }, 300));
        $('#taskStatus, #taskPriority, #taskType').on('change', () => { this.page = 1; this.loadTasks(); });
        $('#taskForm').on('submit', (e) => { e.preventDefault(); this.save(); });

        // Evidence file input
        $('#evidenceFileInput').on('change', (e) => {
            const files = e.target.files;
            if (files.length && this.currentDetailId) {
                this.uploadEvidence(this.currentDetailId, files);
            }
        });
    },

    async loadUsers() {
        try {
            const res = await API.get('/users?per_page=100');
            const users = res.data || [];
            $('#taskAssignee').html('<option value="">Sin asignar</option>' +
                users.map(u => `<option value="${u.id}">${u.first_name} ${u.last_name}</option>`).join(''));
        } catch(e) {}
    },

    async loadTasks() {
        let url = `/tasks?page=${this.page}&per_page=30`;
        const search = $('#taskSearch').val();
        const status = $('#taskStatus').val();
        const priority = $('#taskPriority').val();
        const type = $('#taskType').val();
        if (search) url += `&search=${encodeURIComponent(search)}`;
        if (status) url += `&status=${status}`;
        if (priority) url += `&priority=${priority}`;
        if (type) url += `&task_type=${type}`;

        try {
            const res = await API.get(url);
            this.renderTasks(res.data || []);
            this.updateStats(res.data || []);
            if (res.meta) App.renderPagination('#tasksPagination', res.meta, (p) => { this.page = p; this.loadTasks(); });
        } catch(e) {
            $('#tasksContainer').html('<div class="text-center text-muted" style="padding:2rem">Error al cargar tareas</div>');
        }
    },

    renderTasks(tasks) {
        if (!tasks.length) {
            $('#tasksContainer').html('<div class="empty-state" style="padding:3rem"><p>Sin tareas registradas</p><p class="text-muted">Crea tareas para organizar el trabajo del rancho</p></div>');
            return;
        }
        const today = new Date().toISOString().split('T')[0];
        const priorityLabels = { urgent: 'Urgente', high: 'Alta', medium: 'Media', low: 'Baja' };
        const statusLabels = { pending: 'Pendiente', in_progress: 'En progreso', completed: 'Completada', cancelled: 'Cancelada' };
        const typeLabels = { general: 'General', sanitary: 'Sanitaria', feeding: 'Alimentación', reproductive: 'Reproductiva', cleaning: 'Limpieza', sale: 'Venta/Embarque', veterinary: 'Veterinaria' };

        const html = tasks.map(t => {
            const isOverdue = t.due_date && t.due_date < today && t.status !== 'completed';
            const isToday = t.due_date === today;
            const dueLabel = t.due_date ? App.formatDate(t.due_date) : '';

            const nextStatus = t.status === 'pending' ? 'in_progress' : t.status === 'in_progress' ? 'completed' : null;
            const actionBtn = nextStatus
                ? `<button class="btn btn-sm btn-ghost" onclick="Tasks.setStatus(${t.id}, '${nextStatus}')" title="${nextStatus === 'in_progress' ? 'Iniciar' : 'Completar'}">
                    ${nextStatus === 'completed' ? Icons.checkCircle(14) : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>'}
                   </button>`
                : '';

            return `<div class="task-card priority-${t.priority || 'medium'} ${t.status === 'completed' ? 'completed' : ''} ${isOverdue ? 'overdue' : ''} ${isToday ? 'due-today' : ''}" onclick="Tasks.showDetail(${t.id})" style="cursor:pointer">
                <div class="task-actions">
                    ${actionBtn}
                    <button class="btn btn-sm btn-ghost" onclick="event.stopPropagation();Tasks.edit(${t.id})">${Icons.edit(14)}</button>
                    <button class="btn btn-sm btn-ghost text-danger" onclick="event.stopPropagation();Tasks.deleteTask(${t.id})">${Icons.trash(14)}</button>
                </div>
                <div class="task-title">${t.title}</div>
                ${t.description ? `<div class="task-desc">${t.description.substring(0, 120)}</div>` : ''}
                <div class="task-meta">
                    <span class="task-chip type">${typeLabels[t.task_type] || t.task_type || 'General'}</span>
                    <span class="task-chip status-${t.status}">${statusLabels[t.status] || t.status || 'Pendiente'}</span>
                    <span class="task-chip priority-chip-${t.priority || 'medium'}">${priorityLabels[t.priority] || 'Media'}</span>
                    ${dueLabel ? `<span class="task-chip ${isOverdue ? 'overdue' : isToday ? 'today' : 'due'}">${isOverdue ? '⚠ ' : isToday ? '📌 ' : '📅 '}${dueLabel}</span>` : ''}
                    ${t.assigned_name ? `<span class="task-chip type">${Icons.user(12)} ${t.assigned_name}</span>` : ''}
                </div>
            </div>`;
        }).join('');
        $('#tasksContainer').html(html);
    },

    updateStats(tasks) {
        const today = new Date().toISOString().split('T')[0];
        const pending = tasks.filter(t => t.status === 'pending').length;
        const inProgress = tasks.filter(t => t.status === 'in_progress').length;
        const completed = tasks.filter(t => t.status === 'completed').length;
        const overdue = tasks.filter(t => t.due_date && t.due_date < today && t.status !== 'completed').length;

        if (typeof App.animateCounter === 'function') {
            const $p = $('#statPending')[0];
            const $i = $('#statInProgress')[0];
            const $c = $('#statCompleted')[0];
            const $o = $('#statOverdue')[0];
            if ($p) App.animateCounter($p, pending, 600);
            if ($i) App.animateCounter($i, inProgress, 600);
            if ($c) App.animateCounter($c, completed, 600);
            if ($o) App.animateCounter($o, overdue, 600);
        } else {
            $('#statPending').text(pending);
            $('#statInProgress').text(inProgress);
            $('#statCompleted').text(completed);
            $('#statOverdue').text(overdue);
        }
    },

    showCreateModal() {
        $('#taskModalTitle').text('Nueva Tarea');
        $('#taskForm')[0].reset();
        $('#taskId').val('');
        Modal.open('taskModal');
    },

    async edit(id) {
        try {
            const res = await API.get(`/tasks/${id}`);
            const t = res.data;
            $('#taskModalTitle').text('Editar Tarea');
            $('#taskId').val(t.id);
            $('#taskTitle').val(t.title);
            $('#taskDesc').val(t.description || '');
            $('#taskTaskType').val(t.task_type || 'general');
            $('#taskPriorityField').val(t.priority || 'medium');
            $('#taskDueDate').val(t.due_date || '');
            $('#taskAssignee').val(t.assigned_to || '');
            Modal.open('taskModal');
        } catch(e) { Toast.danger('Error al cargar tarea'); }
    },

    async save() {
        const id = $('#taskId').val();
        const assignee = $('#taskAssignee').val();
        const data = {
            title: $('#taskTitle').val(),
            description: $('#taskDesc').val() || null,
            task_type: $('#taskTaskType').val(),
            priority: $('#taskPriorityField').val(),
            due_date: $('#taskDueDate').val() || null,
            assigned_to: assignee ? [assignee] : [],
        };
        if (!data.title) { Toast.warning('El título es obligatorio'); return; }
        try {
            if (id) await API.put(`/tasks/${id}`, data);
            else await API.post('/tasks', data);
            Modal.close('taskModal');
            Toast.success(id ? 'Tarea actualizada' : 'Tarea creada');
            this.loadTasks();
        } catch(e) { Toast.danger('Error al guardar'); }
    },

    async setStatus(id, status) {
        try {
            if (status === 'completed') {
                await API.put(`/tasks/${id}/complete`, {});
            } else {
                await API.put(`/tasks/${id}`, { status });
            }
            Toast.success(status === 'completed' ? 'Tarea completada ✓' : status === 'in_progress' ? 'Tarea en progreso' : 'Estado actualizado');
            this.loadTasks();
        } catch(e) { Toast.danger('Error al actualizar estado'); }
    },

    async complete(id) {
        return this.setStatus(id, 'completed');
    },

    async deleteTask(id) {
        if (!confirm('¿Eliminar esta tarea?')) return;
        try { await API.delete(`/tasks/${id}`); Toast.success('Eliminada'); this.loadTasks(); } catch(e) { Toast.danger('Error'); }
    },

    // ─── TASK DETAIL WITH EVIDENCE ──────────────────────────

    async showDetail(id) {
        this.currentDetailId = id;
        try {
            const res = await API.get(`/tasks/${id}`);
            const t = res.data;
            const priorityLabels = { urgent:'Urgente', high:'Alta', medium:'Media', low:'Baja' };
            const statusLabels = { pending:'Pendiente', in_progress:'En progreso', completed:'Completada', cancelled:'Cancelada' };
            const typeLabels = { general:'General', health:'Sanitaria', feeding:'Alimentación', reproduction:'Reproductiva', cleaning:'Limpieza', sales:'Venta/Embarque' };

            $('#taskDetailTitle').text(t.title || 'Detalle de Tarea');
            let assignees = '';
            if (t.assignments && t.assignments.length) {
                assignees = t.assignments.map(a => `${a.first_name} ${a.last_name}`).join(', ');
            } else if (t.assignees) {
                assignees = t.assignees;
            }

            let html = `<div class="task-detail-info">`;
            if (t.description) {
                html += `<div><div class="task-detail-label">Descripción</div><div class="task-detail-desc">${App.escapeHtml(t.description)}</div></div>`;
            }
            html += `<div class="task-detail-row">
                <div style="flex:1"><div class="task-detail-label">Tipo</div><div class="task-detail-value"><span class="task-chip type">${typeLabels[t.task_type]||t.task_type||'General'}</span></div></div>
                <div style="flex:1"><div class="task-detail-label">Prioridad</div><div class="task-detail-value"><span class="task-chip priority-chip-${t.priority||'medium'}">${priorityLabels[t.priority]||'Media'}</span></div></div>
                <div style="flex:1"><div class="task-detail-label">Estado</div><div class="task-detail-value"><span class="task-chip status-${t.status}">${statusLabels[t.status]||t.status}</span></div></div>
            </div>`;
            html += `<div class="task-detail-row">`;
            if (t.due_date) html += `<div style="flex:1"><div class="task-detail-label">Fecha límite</div><div class="task-detail-value">${App.formatDate(t.due_date)}</div></div>`;
            if (assignees) html += `<div style="flex:1"><div class="task-detail-label">Asignada a</div><div class="task-detail-value">${App.escapeHtml(assignees)}</div></div>`;
            html += `</div>`;
            if (t.completed_at) {
                html += `<div><div class="task-detail-label">Completada el</div><div class="task-detail-value">${App.formatDateTime(t.completed_at)}</div></div>`;
            }
            html += `</div>`;
            $('#taskDetailBody').html(html);

            // Load evidence
            this.loadEvidence(id);

            Modal.open('taskDetailModal');
        } catch(e) {
            Toast.danger('Error al cargar tarea');
        }
    },

    async loadEvidence(taskId) {
        const gallery = document.getElementById('evidenceGallery');
        const emptyEl = document.getElementById('evidenceEmpty');
        const countEl = document.getElementById('evidenceCount');

        try {
            const res = await API.get(`/tasks/${taskId}/evidence`);
            const items = res.data || [];

            countEl.textContent = items.length;

            if (!items.length) {
                gallery.innerHTML = `<div class="evidence-empty" id="evidenceEmpty">
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="opacity:0.3"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                    <span>Sin evidencias adjuntas</span>
                </div>`;
                return;
            }

            let html = '';
            items.forEach(ev => {
                const isImage = ev.file_type && ev.file_type.startsWith('image/');
                if (isImage) {
                    html += `<div class="evidence-item" onclick="Tasks.showLightbox('${ev.file_path}')">
                        <img src="${ev.file_path}" alt="Evidencia" loading="lazy">
                        <button class="evidence-delete" onclick="event.stopPropagation();Tasks.deleteEvidenceItem(${ev.id})" title="Eliminar">×</button>
                        ${ev.caption ? `<div class="evidence-caption">${App.escapeHtml(ev.caption)}</div>` : ''}
                    </div>`;
                } else {
                    html += `<div class="evidence-item" onclick="window.open('${ev.file_path}','_blank')">
                        <div class="evidence-pdf-icon">📄</div>
                        <button class="evidence-delete" onclick="event.stopPropagation();Tasks.deleteEvidenceItem(${ev.id})" title="Eliminar">×</button>
                        ${ev.caption ? `<div class="evidence-caption">${App.escapeHtml(ev.caption)}</div>` : `<div class="evidence-caption">PDF</div>`}
                    </div>`;
                }
            });
            gallery.innerHTML = html;
        } catch(e) {
            gallery.innerHTML = '<div class="evidence-empty"><span>Error al cargar evidencias</span></div>';
        }
    },

    async uploadEvidence(taskId, files) {
        const uploading = document.getElementById('evidenceUploading');
        const progressFill = document.getElementById('evidenceProgressFill');
        uploading.style.display = 'flex';
        progressFill.style.width = '10%';

        let uploaded = 0;
        for (const file of files) {
            try {
                const fd = new FormData();
                fd.append('evidence', file);
                await API.upload(`/tasks/${taskId}/evidence`, fd);
                uploaded++;
                progressFill.style.width = `${Math.round((uploaded / files.length) * 100)}%`;
            } catch(e) {
                Toast.danger(`Error subiendo ${file.name}`);
            }
        }

        uploading.style.display = 'none';
        progressFill.style.width = '0%';
        document.getElementById('evidenceFileInput').value = '';

        if (uploaded > 0) {
            Toast.success(`${uploaded} evidencia(s) subida(s)`);
            this.loadEvidence(taskId);
        }
    },

    async deleteEvidenceItem(evidenceId) {
        if (!confirm('¿Eliminar esta evidencia?')) return;
        try {
            await API.delete(`/task-evidence/${evidenceId}`);
            Toast.success('Evidencia eliminada');
            if (this.currentDetailId) {
                this.loadEvidence(this.currentDetailId);
            }
        } catch(e) {
            Toast.danger('Error al eliminar');
        }
    },

    showLightbox(src) {
        const existing = document.querySelector('.evidence-lightbox');
        if (existing) existing.remove();

        const lb = document.createElement('div');
        lb.className = 'evidence-lightbox';
        lb.innerHTML = `
            <button class="evidence-lightbox-close" onclick="this.parentElement.remove()">×</button>
            <img src="${src}" alt="Evidencia">
        `;
        lb.addEventListener('click', function(e) {
            if (e.target === lb) lb.remove();
        });
        document.body.appendChild(lb);
    }
};

$(document).ready(() => Tasks.init());
