/**
 * Pomodoro Timer - Task Management Module
 * 
 * Developer: Molla Samser (Founder, RSK World)
 * Designer: Rima Khatun (Designer & Tester, RSK World)
 * Website: https://rskworld.in/
 * Contact: +91 93305 39277 | hello@rskworld.in | support@rskworld.in
 * Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
 * Year: 2026
 * 
 * Description: Task management system for Pomodoro Timer
 */

class TaskManager {
    constructor() {
        this.tasks = this.loadTasks();
        this.currentTask = null;
        this.categories = ['Work', 'Study', 'Personal', 'Health'];
        this.priorities = ['low', 'medium', 'high', 'urgent'];
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.renderTasks();
        this.updateStats();
    }

    setupEventListeners() {
        // Add task form
        const addTaskBtn = document.getElementById('add-task-btn');
        const taskModal = document.getElementById('task-modal');
        const closeTaskModal = document.getElementById('close-task-modal');
        const taskForm = document.getElementById('task-form');

        if (addTaskBtn) {
            addTaskBtn.addEventListener('click', () => this.showTaskModal());
        }

        if (closeTaskModal) {
            closeTaskModal.addEventListener('click', () => this.hideTaskModal());
        }

        if (taskForm) {
            taskForm.addEventListener('submit', (e) => this.handleTaskSubmit(e));
        }

        // Task filters
        const filterButtons = document.querySelectorAll('.task-filter');
        filterButtons.forEach(btn => {
            btn.addEventListener('click', (e) => this.handleFilterChange(e));
        });

        // Search functionality
        const searchInput = document.getElementById('task-search');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => this.handleSearch(e.target.value));
        }
    }

    showTaskModal(task = null) {
        const modal = document.getElementById('task-modal');
        const form = document.getElementById('task-form');
        
        if (task) {
            // Edit mode
            form.dataset.taskId = task.id;
            document.getElementById('task-title').value = task.title;
            document.getElementById('task-description').value = task.description || '';
            document.getElementById('task-category').value = task.category;
            document.getElementById('task-priority').value = task.priority;
            document.getElementById('task-estimated-pomodoros').value = task.estimatedPomodoros || 1;
        } else {
            // Add mode
            delete form.dataset.taskId;
            form.reset();
        }

        modal.classList.add('active');
    }

    hideTaskModal() {
        const modal = document.getElementById('task-modal');
        modal.classList.remove('active');
    }

    handleTaskSubmit(e) {
        e.preventDefault();
        
        const form = e.target;
        const taskId = form.dataset.taskId;
        
        const taskData = {
            title: document.getElementById('task-title').value.trim(),
            description: document.getElementById('task-description').value.trim(),
            category: document.getElementById('task-category').value,
            priority: document.getElementById('task-priority').value,
            estimatedPomodoros: parseInt(document.getElementById('task-estimated-pomodoros').value) || 1,
            createdAt: new Date().toISOString()
        };

        if (taskId) {
            // Update existing task
            this.updateTask(taskId, taskData);
        } else {
            // Add new task
            this.addTask(taskData);
        }

        this.hideTaskModal();
    }

    addTask(taskData) {
        const task = {
            id: this.generateId(),
            ...taskData,
            status: 'active',
            completedPomodoros: 0,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };

        this.tasks.push(task);
        this.saveTasks();
        this.renderTasks();
        this.updateStats();

        // Show notification
        this.showNotification('Task added successfully', 'success');
    }

    updateTask(taskId, updates) {
        const taskIndex = this.tasks.findIndex(task => task.id === taskId);
        if (taskIndex !== -1) {
            this.tasks[taskIndex] = {
                ...this.tasks[taskIndex],
                ...updates,
                updatedAt: new Date().toISOString()
            };
            this.saveTasks();
            this.renderTasks();
            this.updateStats();
            this.showNotification('Task updated successfully', 'success');
        }
    }

    deleteTask(taskId) {
        if (confirm('Are you sure you want to delete this task?')) {
            this.tasks = this.tasks.filter(task => task.id !== taskId);
            this.saveTasks();
            this.renderTasks();
            this.updateStats();
            this.showNotification('Task deleted successfully', 'info');
        }
    }

    completeTask(taskId) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            task.status = 'completed';
            task.completedAt = new Date().toISOString();
            task.updatedAt = new Date().toISOString();
            this.saveTasks();
            this.renderTasks();
            this.updateStats();
            this.showNotification('Task completed! Great job!', 'success');
        }
    }

    setCurrentTask(taskId) {
        this.currentTask = this.tasks.find(task => task.id === taskId) || null;
        this.renderTasks();
        
        // Update UI to show current task
        const currentTaskElement = document.getElementById('current-task-display');
        if (currentTaskElement) {
            if (this.currentTask) {
                currentTaskElement.innerHTML = `
                    <div class="current-task-info">
                        <h4>${this.currentTask.title}</h4>
                        <div class="task-progress">
                            <span>${this.currentTask.completedPomodoros}/${this.currentTask.estimatedPomodoros} Pomodoros</span>
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: ${(this.currentTask.completedPomodoros / this.currentTask.estimatedPomodoros) * 100}%"></div>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                currentTaskElement.innerHTML = '<p>No active task selected</p>';
            }
        }
    }

    incrementTaskPomodoros(taskId) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            task.completedPomodoros++;
            task.updatedAt = new Date().toISOString();
            
            // Check if task is completed
            if (task.completedPomodoros >= task.estimatedPomodoros) {
                task.status = 'completed';
                task.completedAt = new Date().toISOString();
                this.showNotification(`Task "${task.title}" completed!`, 'success');
            }
            
            this.saveTasks();
            this.renderTasks();
            this.updateStats();
        }
    }

    renderTasks() {
        const container = document.getElementById('tasks-list');
        if (!container) return;

        const filteredTasks = this.getFilteredTasks();
        
        if (filteredTasks.length === 0) {
            container.innerHTML = '<div class="no-tasks">No tasks found. Add your first task!</div>';
            return;
        }

        container.innerHTML = filteredTasks.map(task => this.createTaskElement(task)).join('');
        
        // Add event listeners to task elements
        container.querySelectorAll('.task-actions button').forEach(btn => {
            btn.addEventListener('click', (e) => this.handleTaskAction(e));
        });
    }

    createTaskElement(task) {
        const isCurrent = this.currentTask && this.currentTask.id === task.id;
        const progress = (task.completedPomodoros / task.estimatedPomodoros) * 100;
        
        return `
            <div class="task-item ${task.status} ${isCurrent ? 'current' : ''}" data-task-id="${task.id}">
                <div class="task-header">
                    <h3 class="task-title">${task.title}</h3>
                    <span class="task-priority ${task.priority}">${task.priority}</span>
                </div>
                ${task.description ? `<p class="task-description">${task.description}</p>` : ''}
                <div class="task-meta">
                    <span class="task-category">${task.category}</span>
                    <span class="task-pomodoros">${task.completedPomodoros}/${task.estimatedPomodoros} Pomodoros</span>
                </div>
                <div class="task-progress">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${progress}%"></div>
                    </div>
                </div>
                <div class="task-actions">
                    ${task.status !== 'completed' ? `
                        <button class="btn btn-primary btn-sm" data-action="select" title="Select as current task">
                            <i class="fas fa-play"></i>
                        </button>
                        <button class="btn btn-secondary btn-sm" data-action="edit" title="Edit task">
                            <i class="fas fa-edit"></i>
                        </button>
                    ` : ''}
                    <button class="btn btn-success btn-sm" data-action="complete" title="Mark as complete">
                        <i class="fas fa-check"></i>
                    </button>
                    <button class="btn btn-danger btn-sm" data-action="delete" title="Delete task">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }

    handleTaskAction(e) {
        const button = e.currentTarget;
        const action = button.dataset.action;
        const taskId = button.closest('.task-item').dataset.taskId;
        
        switch (action) {
            case 'select':
                this.setCurrentTask(taskId);
                break;
            case 'edit':
                const task = this.tasks.find(t => t.id === taskId);
                if (task) this.showTaskModal(task);
                break;
            case 'complete':
                this.completeTask(taskId);
                break;
            case 'delete':
                this.deleteTask(taskId);
                break;
        }
    }

    handleFilterChange(e) {
        const filter = e.target.dataset.filter;
        document.querySelectorAll('.task-filter').forEach(btn => btn.classList.remove('active'));
        e.target.classList.add('active');
        this.currentFilter = filter;
        this.renderTasks();
    }

    handleSearch(query) {
        this.searchQuery = query.toLowerCase();
        this.renderTasks();
    }

    getFilteredTasks() {
        let filtered = [...this.tasks];
        
        // Apply status filter
        if (this.currentFilter && this.currentFilter !== 'all') {
            filtered = filtered.filter(task => task.status === this.currentFilter);
        }
        
        // Apply search filter
        if (this.searchQuery) {
            filtered = filtered.filter(task => 
                task.title.toLowerCase().includes(this.searchQuery) ||
                (task.description && task.description.toLowerCase().includes(this.searchQuery)) ||
                task.category.toLowerCase().includes(this.searchQuery)
            );
        }
        
        // Sort by priority and creation date
        return filtered.sort((a, b) => {
            const priorityOrder = { urgent: 4, high: 3, medium: 2, low: 1 };
            if (priorityOrder[b.priority] !== priorityOrder[a.priority]) {
                return priorityOrder[b.priority] - priorityOrder[a.priority];
            }
            return new Date(b.createdAt) - new Date(a.createdAt);
        });
    }

    updateStats() {
        const stats = this.getTaskStats();
        const statsElement = document.getElementById('task-stats');
        
        if (statsElement) {
            statsElement.innerHTML = `
                <div class="stat-item">
                    <span class="stat-value">${stats.total}</span>
                    <span class="stat-label">Total Tasks</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${stats.active}</span>
                    <span class="stat-label">Active</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${stats.completed}</span>
                    <span class="stat-label">Completed</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${stats.totalPomodoros}</span>
                    <span class="stat-label">Total Pomodoros</span>
                </div>
            `;
        }
    }

    getTaskStats() {
        return {
            total: this.tasks.length,
            active: this.tasks.filter(t => t.status === 'active').length,
            completed: this.tasks.filter(t => t.status === 'completed').length,
            totalPomodoros: this.tasks.reduce((sum, task) => sum + task.completedPomodoros, 0)
        };
    }

    showNotification(message, type = 'info') {
        // Use the existing notification system or create a simple one
        if (window.pomodoroApp && window.pomodoroApp.showNotification) {
            window.pomodoroApp.showNotification(message, type);
        } else {
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
    }

    generateId() {
        return 'task_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    saveTasks() {
        try {
            localStorage.setItem('pomodoro_tasks', JSON.stringify(this.tasks));
        } catch (error) {
            console.error('Failed to save tasks:', error);
        }
    }

    loadTasks() {
        try {
            const saved = localStorage.getItem('pomodoro_tasks');
            return saved ? JSON.parse(saved) : [];
        } catch (error) {
            console.error('Failed to load tasks:', error);
            return [];
        }
    }

    exportTasks() {
        const data = {
            tasks: this.tasks,
            exportDate: new Date().toISOString(),
            version: '1.0.0'
        };
        
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `pomodoro-tasks-${new Date().toISOString().split('T')[0]}.json`;
        a.click();
        URL.revokeObjectURL(url);
    }

    importTasks(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    if (data.tasks && Array.isArray(data.tasks)) {
                        this.tasks = data.tasks;
                        this.saveTasks();
                        this.renderTasks();
                        this.updateStats();
                        resolve(data.tasks.length);
                    } else {
                        reject(new Error('Invalid file format'));
                    }
                } catch (error) {
                    reject(error);
                }
            };
            reader.onerror = () => reject(new Error('Failed to read file'));
            reader.readAsText(file);
        });
    }
}

// Initialize task manager when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.taskManager = new TaskManager();
});
