/**
 * Pomodoro Timer - Export/Import Manager
 * 
 * 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: Data export and import functionality for Pomodoro Timer
 */

class DataManager {
    constructor() {
        this.exportFormats = ['json', 'csv', 'pdf'];
        this.importFormats = ['json', 'csv'];
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.createExportControls();
    }

    setupEventListeners() {
        // Export buttons
        document.addEventListener('click', (e) => {
            if (e.target.matches('[data-export]')) {
                const format = e.target.dataset.export;
                const dataType = e.target.dataset.type || 'all';
                this.exportData(format, dataType);
            }
        });

        // Import buttons
        document.addEventListener('click', (e) => {
            if (e.target.matches('[data-import]')) {
                this.showImportDialog();
            }
        });

        // File input for import
        document.addEventListener('change', (e) => {
            if (e.target.matches('#import-file-input')) {
                this.handleFileImport(e.target.files[0]);
            }
        });
    }

    createExportControls() {
        const controlsHTML = `
            <div class="data-controls">
                <div class="export-section">
                    <h3>Export Data</h3>
                    <div class="export-options">
                        <div class="export-group">
                            <label>Data Type:</label>
                            <select id="export-data-type">
                                <option value="all">All Data</option>
                                <option value="sessions">Sessions Only</option>
                                <option value="tasks">Tasks Only</option>
                                <option value="statistics">Statistics Only</option>
                                <option value="settings">Settings Only</option>
                            </select>
                        </div>
                        <div class="export-group">
                            <label>Format:</label>
                            <div class="format-buttons">
                                <button class="btn btn-secondary" data-export="json" data-type="all">JSON</button>
                                <button class="btn btn-secondary" data-export="csv" data-type="all">CSV</button>
                                <button class="btn btn-secondary" data-export="pdf" data-type="all">PDF</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="import-section">
                    <h3>Import Data</h3>
                    <div class="import-options">
                        <button class="btn btn-primary" data-import="json">Import Data</button>
                        <p class="import-help">Import previously exported data from JSON or CSV files</p>
                    </div>
                </div>
                
                <div class="backup-section">
                    <h3>Backup & Restore</h3>
                    <div class="backup-options">
                        <button class="btn btn-warning" id="create-backup">Create Backup</button>
                        <button class="btn btn-info" id="restore-backup">Restore Backup</button>
                        <button class="btn btn-danger" id="clear-all-data">Clear All Data</button>
                    </div>
                </div>
            </div>
        `;

        const settingsContainer = document.querySelector('.settings-content');
        if (settingsContainer) {
            settingsContainer.insertAdjacentHTML('beforeend', controlsHTML);
        }
    }

    exportData(format, dataType = 'all') {
        const data = this.collectData(dataType);
        
        switch (format.toLowerCase()) {
            case 'json':
                this.exportAsJSON(data, dataType);
                break;
            case 'csv':
                this.exportAsCSV(data, dataType);
                break;
            case 'pdf':
                this.exportAsPDF(data, dataType);
                break;
            default:
                console.error('Unsupported export format:', format);
        }
    }

    collectData(dataType) {
        const data = {
            exportInfo: {
                date: new Date().toISOString(),
                version: '1.0.0',
                dataType: dataType
            }
        };

        switch (dataType) {
            case 'all':
                data.sessions = this.getSessionsData();
                data.tasks = this.getTasksData();
                data.statistics = this.getStatisticsData();
                data.settings = this.getSettingsData();
                break;
            case 'sessions':
                data.sessions = this.getSessionsData();
                break;
            case 'tasks':
                data.tasks = this.getTasksData();
                break;
            case 'statistics':
                data.statistics = this.getStatisticsData();
                break;
            case 'settings':
                data.settings = this.getSettingsData();
                break;
        }

        return data;
    }

    getSessionsData() {
        try {
            const sessions = localStorage.getItem('pomodoro_sessions');
            return sessions ? JSON.parse(sessions) : [];
        } catch (error) {
            console.error('Failed to get sessions data:', error);
            return [];
        }
    }

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

    getStatisticsData() {
        try {
            const stats = localStorage.getItem('pomodoro_statistics');
            return stats ? JSON.parse(stats) : {};
        } catch (error) {
            console.error('Failed to get statistics data:', error);
            return {};
        }
    }

    getSettingsData() {
        try {
            const settings = {
                theme: localStorage.getItem('pomodoro_theme'),
                timer: localStorage.getItem('pomodoro_timer_settings'),
                ui: localStorage.getItem('pomodoro_ui_settings')
            };
            return settings;
        } catch (error) {
            console.error('Failed to get settings data:', error);
            return {};
        }
    }

    exportAsJSON(data, dataType) {
        const jsonString = JSON.stringify(data, null, 2);
        const blob = new Blob([jsonString], { type: 'application/json' });
        this.downloadFile(blob, `pomodoro-${dataType}-${this.getDateString()}.json`);
    }

    exportAsCSV(data, dataType) {
        let csvContent = '';
        
        switch (dataType) {
            case 'sessions':
                csvContent = this.sessionsToCSV(data.sessions || []);
                break;
            case 'tasks':
                csvContent = this.tasksToCSV(data.tasks || []);
                break;
            case 'statistics':
                csvContent = this.statisticsToCSV(data.statistics || {});
                break;
            case 'all':
                csvContent = this.allDataToCSV(data);
                break;
            default:
                csvContent = 'No data available for export';
        }

        const blob = new Blob([csvContent], { type: 'text/csv' });
        this.downloadFile(blob, `pomodoro-${dataType}-${this.getDateString()}.csv`);
    }

    exportAsPDF(data, dataType) {
        // Simple PDF generation using jsPDF (would need to include jsPDF library)
        // For now, we'll create a text-based representation
        let content = `Pomodoro Timer Data Export\n`;
        content += `============================\n`;
        content += `Export Date: ${new Date().toLocaleString()}\n`;
        content += `Data Type: ${dataType}\n\n`;

        switch (dataType) {
            case 'sessions':
                content += this.sessionsToText(data.sessions || []);
                break;
            case 'tasks':
                content += this.tasksToText(data.tasks || []);
                break;
            case 'statistics':
                content += this.statisticsToText(data.statistics || {});
                break;
            case 'all':
                content += this.allDataToText(data);
                break;
        }

        const blob = new Blob([content], { type: 'text/plain' });
        this.downloadFile(blob, `pomodoro-${dataType}-${this.getDateString()}.txt`);
    }

    sessionsToCSV(sessions) {
        if (sessions.length === 0) return 'No sessions data';
        
        const headers = ['Date', 'Type', 'Duration', 'Completed', 'Task'];
        const rows = sessions.map(session => [
            new Date(session.date).toLocaleDateString(),
            session.type,
            session.duration,
            session.completed ? 'Yes' : 'No',
            session.task || 'N/A'
        ]);
        
        return this.createCSV(headers, rows);
    }

    tasksToCSV(tasks) {
        if (tasks.length === 0) return 'No tasks data';
        
        const headers = ['Title', 'Category', 'Priority', 'Status', 'Created', 'Completed Pomodoros', 'Estimated Pomodoros'];
        const rows = tasks.map(task => [
            task.title,
            task.category,
            task.priority,
            task.status,
            new Date(task.createdAt).toLocaleDateString(),
            task.completedPomodoros || 0,
            task.estimatedPomodoros || 1
        ]);
        
        return this.createCSV(headers, rows);
    }

    statisticsToCSV(statistics) {
        const headers = ['Metric', 'Value'];
        const rows = Object.entries(statistics).map(([key, value]) => [
            this.formatMetricName(key),
            typeof value === 'object' ? JSON.stringify(value) : value
        ]);
        
        return this.createCSV(headers, rows);
    }

    allDataToCSV(data) {
        let csvContent = '';
        
        if (data.sessions) {
            csvContent += 'SESSIONS\n';
            csvContent += this.sessionsToCSV(data.sessions);
            csvContent += '\n\n';
        }
        
        if (data.tasks) {
            csvContent += 'TASKS\n';
            csvContent += this.tasksToCSV(data.tasks);
            csvContent += '\n\n';
        }
        
        if (data.statistics) {
            csvContent += 'STATISTICS\n';
            csvContent += this.statisticsToCSV(data.statistics);
        }
        
        return csvContent;
    }

    createCSV(headers, rows) {
        const csvHeaders = headers.join(',');
        const csvRows = rows.map(row => 
            row.map(cell => `"${cell}"`).join(',')
        );
        return [csvHeaders, ...csvRows].join('\n');
    }

    sessionsToText(sessions) {
        if (sessions.length === 0) return 'No sessions data';
        
        let text = 'Sessions\n--------\n';
        sessions.forEach(session => {
            text += `Date: ${new Date(session.date).toLocaleString()}\n`;
            text += `Type: ${session.type}\n`;
            text += `Duration: ${session.duration} minutes\n`;
            text += `Completed: ${session.completed ? 'Yes' : 'No'}\n`;
            text += `Task: ${session.task || 'N/A'}\n\n`;
        });
        return text;
    }

    tasksToText(tasks) {
        if (tasks.length === 0) return 'No tasks data';
        
        let text = 'Tasks\n-----\n';
        tasks.forEach(task => {
            text += `Title: ${task.title}\n`;
            text += `Category: ${task.category}\n`;
            text += `Priority: ${task.priority}\n`;
            text += `Status: ${task.status}\n`;
            text += `Created: ${new Date(task.createdAt).toLocaleDateString()}\n`;
            text += `Progress: ${task.completedPomodoros || 0}/${task.estimatedPomodoros || 1}\n\n`;
        });
        return text;
    }

    statisticsToText(statistics) {
        let text = 'Statistics\n-----------\n';
        Object.entries(statistics).forEach(([key, value]) => {
            text += `${this.formatMetricName(key)}: ${typeof value === 'object' ? JSON.stringify(value) : value}\n`;
        });
        return text;
    }

    allDataToText(data) {
        let text = '';
        
        if (data.sessions) {
            text += this.sessionsToText(data.sessions) + '\n';
        }
        
        if (data.tasks) {
            text += this.tasksToText(data.tasks) + '\n';
        }
        
        if (data.statistics) {
            text += this.statisticsToText(data.statistics);
        }
        
        return text;
    }

    showImportDialog() {
        const modal = document.getElementById('import-modal');
        if (!modal) {
            this.createImportModal();
        }
        
        const modalElement = document.getElementById('import-modal');
        modalElement.classList.add('active');
    }

    createImportModal() {
        const modalHTML = `
            <div id="import-modal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2>Import Data</h2>
                        <button id="close-import-modal" class="btn-close">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="import-instructions">
                            <p>Select a previously exported file to import your data.</p>
                            <p><strong>Note:</strong> Importing will merge with existing data. Duplicates will be skipped.</p>
                        </div>
                        <div class="file-input-group">
                            <input type="file" id="import-file-input" accept=".json,.csv" />
                            <label for="import-file-input" class="btn btn-primary">Choose File</label>
                        </div>
                        <div id="import-preview" class="import-preview"></div>
                    </div>
                    <div class="modal-footer">
                        <button id="confirm-import" class="btn btn-success" disabled>Import Data</button>
                        <button id="cancel-import" class="btn btn-secondary">Cancel</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        this.setupImportModalEvents();
    }

    setupImportModalEvents() {
        const closeBtn = document.getElementById('close-import-modal');
        const cancelBtn = document.getElementById('cancel-import');
        const confirmBtn = document.getElementById('confirm-import');

        if (closeBtn) closeBtn.addEventListener('click', () => this.hideImportDialog());
        if (cancelBtn) cancelBtn.addEventListener('click', () => this.hideImportDialog());
        if (confirmBtn) confirmBtn.addEventListener('click', () => this.confirmImport());
    }

    hideImportDialog() {
        const modal = document.getElementById('import-modal');
        if (modal) {
            modal.classList.remove('active');
            // Reset form
            document.getElementById('import-file-input').value = '';
            document.getElementById('import-preview').innerHTML = '';
            document.getElementById('confirm-import').disabled = true;
        }
    }

    async handleFileImport(file) {
        if (!file) return;

        const preview = document.getElementById('import-preview');
        const confirmBtn = document.getElementById('confirm-import');

        try {
            const content = await this.readFile(file);
            const data = this.parseFileContent(content, file.name);
            
            // Show preview
            preview.innerHTML = this.createImportPreview(data);
            confirmBtn.disabled = false;
            
            // Store data for import
            this.pendingImportData = data;
            
        } catch (error) {
            preview.innerHTML = `<div class="error">Error reading file: ${error.message}</div>`;
            confirmBtn.disabled = true;
        }
    }

    readFile(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = () => reject(new Error('Failed to read file'));
            reader.readAsText(file);
        });
    }

    parseFileContent(content, filename) {
        const extension = filename.split('.').pop().toLowerCase();
        
        switch (extension) {
            case 'json':
                return JSON.parse(content);
            case 'csv':
                return this.parseCSV(content);
            default:
                throw new Error('Unsupported file format');
        }
    }

    parseCSV(content) {
        // Simple CSV parser (for basic CSV files)
        const lines = content.split('\n').filter(line => line.trim());
        if (lines.length < 2) throw new Error('Invalid CSV format');
        
        const headers = lines[0].split(',').map(h => h.replace(/"/g, '').trim());
        const data = [];
        
        for (let i = 1; i < lines.length; i++) {
            const values = lines[i].split(',').map(v => v.replace(/"/g, '').trim());
            const row = {};
            headers.forEach((header, index) => {
                row[header] = values[index] || '';
            });
            data.push(row);
        }
        
        return { data, format: 'csv' };
    }

    createImportPreview(data) {
        let preview = '<div class="import-summary"><h3>Import Preview</h3>';
        
        if (data.sessions) {
            preview += `<p>Sessions: ${data.sessions.length}</p>`;
        }
        if (data.tasks) {
            preview += `<p>Tasks: ${data.tasks.length}</p>`;
        }
        if (data.data && Array.isArray(data.data)) {
            preview += `<p>Records: ${data.data.length}</p>`;
        }
        
        preview += '</div>';
        return preview;
    }

    confirmImport() {
        if (!this.pendingImportData) return;

        try {
            this.importData(this.pendingImportData);
            this.hideImportDialog();
            
            if (window.pomodoroApp && window.pomodoroApp.showNotification) {
                window.pomodoroApp.showNotification('Data imported successfully', 'success');
            }
            
            // Refresh UI
            if (window.taskManager) {
                window.taskManager.renderTasks();
                window.taskManager.updateStats();
            }
            
        } catch (error) {
            console.error('Import failed:', error);
            if (window.pomodoroApp && window.pomodoroApp.showNotification) {
                window.pomodoroApp.showNotification('Import failed: ' + error.message, 'error');
            }
        }
    }

    importData(data) {
        // Import sessions
        if (data.sessions && Array.isArray(data.sessions)) {
            const existingSessions = this.getSessionsData();
            const mergedSessions = this.mergeData(existingSessions, data.sessions, 'date');
            localStorage.setItem('pomodoro_sessions', JSON.stringify(mergedSessions));
        }

        // Import tasks
        if (data.tasks && Array.isArray(data.tasks)) {
            const existingTasks = this.getTasksData();
            const mergedTasks = this.mergeData(existingTasks, data.tasks, 'id');
            localStorage.setItem('pomodoro_tasks', JSON.stringify(mergedTasks));
        }

        // Import settings
        if (data.settings) {
            Object.entries(data.settings).forEach(([key, value]) => {
                if (value) {
                    localStorage.setItem(`pomodoro_${key}`, typeof value === 'string' ? value : JSON.stringify(value));
                }
            });
        }
    }

    mergeData(existing, incoming, uniqueKey) {
        const merged = [...existing];
        const existingKeys = new Set(existing.map(item => item[uniqueKey]));
        
        incoming.forEach(item => {
            if (!existingKeys.has(item[uniqueKey])) {
                merged.push(item);
            }
        });
        
        return merged;
    }

    createBackup() {
        const backup = this.collectData('all');
        backup.backupInfo = {
            version: '1.0.0',
            created: new Date().toISOString(),
            type: 'full_backup'
        };
        
        const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
        this.downloadFile(blob, `pomodoro-backup-${this.getDateString()}.json`);
        
        if (window.pomodoroApp && window.pomodoroApp.showNotification) {
            window.pomodoroApp.showNotification('Backup created successfully', 'success');
        }
    }

    clearAllData() {
        if (confirm('Are you sure you want to clear all data? This action cannot be undone.')) {
            const keys = Object.keys(localStorage).filter(key => key.startsWith('pomodoro_'));
            keys.forEach(key => localStorage.removeItem(key));
            
            if (window.pomodoroApp && window.pomodoroApp.showNotification) {
                window.pomodoroApp.showNotification('All data cleared successfully', 'info');
            }
            
            // Refresh page to reset state
            setTimeout(() => location.reload(), 1000);
        }
    }

    downloadFile(blob, filename) {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        URL.revokeObjectURL(url);
    }

    getDateString() {
        return new Date().toISOString().split('T')[0];
    }

    formatMetricName(key) {
        return key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
    }
}

// Initialize data manager when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.dataManager = new DataManager();
});
