import './bootstrap';
// import './task-editor';

import Alpine from 'alpinejs';
import collapse from '@alpinejs/collapse';
import Sortable from 'sortablejs';

Alpine.plugin(collapse);

window.Sortable = Sortable;

// Define taskManager BEFORE Alpine starts
const taskManager = () => ({
    view: 'list',
    isModalOpen: false,
    init() {
        this.initSortable();
    },
    initSortable() {
        // Kanban Columns
        document.querySelectorAll('[x-ref^="kanban_"]').forEach(el => {
            new Sortable(el, {
                group: 'kanban',
                animation: 150,
                ghostClass: 'bg-indigo-100',
                onEnd: (evt) => {
                    const taskId = evt.item.dataset.id;
                    const columnId = evt.to.dataset.columnId;

                    axios.patch(`/tasks/${taskId}`, { kanban_column_id: columnId })
                        .then(response => {
                            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Task moved', type: 'success' } }));
                        })
                        .catch(error => {
                            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Failed to move task', type: 'error' } }));
                        });
                }
            });
        });

        // List View Sorting
        const listEl = this.$refs.taskList;
        if (listEl) {
            new Sortable(listEl, {
                animation: 150,
                handle: '.cursor-grab',
                onEnd: (evt) => {
                    const itemEl = evt.item;
                    const newIndex = evt.newIndex;
                    const oldIndex = evt.oldIndex;

                    // Gather new order
                    const orders = [];
                    Array.from(listEl.children).forEach((child, index) => {
                        orders.push({ id: child.dataset.id, order_index: index });
                    });

                    axios.patch('/tasks/reorder', { orders })
                        .then(() => {
                            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Order updated', type: 'success' } }));
                        })
                        .catch(() => {
                            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Failed to reorder', type: 'error' } }));
                        });
                }
            });
        }
    }
});

// Expose to window for spread syntax
window.taskManager = taskManager;

// Register dashboard component
Alpine.data('dashboardComponent', (initialView = 'list') => ({
    view: initialView,
    isModalOpen: false,

    init() {
        console.log('✅ Dashboard Alpine initialized');

        // Listen for view changes from sidebar
        window.addEventListener('change-view', (e) => {
            console.log('Changing view to:', e.detail);
            this.view = e.detail;
            if (this.view === 'kanban') {
                this.$nextTick(() => this.initSortable());
            }
        });

        this.$nextTick(() => {
            if (typeof window.Sortable !== 'undefined') {
                this.initSortable();
            }
        });
    },

    initSortable() {
        console.log('Initializing Sortable...');
        // Kanban Columns
        document.querySelectorAll('[x-ref^="kanban_"]').forEach(el => {
            new Sortable(el, {
                group: 'kanban',
                animation: 150,
                ghostClass: 'bg-indigo-100',
                onEnd: (evt) => {
                    const taskId = evt.item.dataset.id;
                    const columnId = evt.to.dataset.columnId;
                    axios.patch(`/tasks/${taskId}`, { kanban_column_id: columnId })
                        .then(() => {
                            console.log('Task moved');
                        })
                        .catch(error => console.error('Error moving task:', error));
                }
            });
        });

        // Kanban Container (Column Reordering)
        const kanbanContainer = this.$refs.kanbanContainer;
        if (kanbanContainer) {
            new Sortable(kanbanContainer, {
                animation: 150,
                draggable: '.kanban-column',
                onEnd: (evt) => {
                    const columns = [];
                    Array.from(kanbanContainer.querySelectorAll('.kanban-column')).forEach((child, index) => {
                        columns.push({ id: child.dataset.id, order_index: index });
                    });
                    axios.patch('/kanban-columns/reorder', { columns })
                        .then(() => {
                            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Columns reordered', type: 'success' } }));
                        })
                        .catch(error => {
                            console.error('Error reordering columns:', error);
                            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Failed to reorder columns', type: 'error' } }));
                        });
                }
            });
        }

        // List View Sorting
        const listEl = this.$refs.taskList;
        if (listEl) {
            new Sortable(listEl, {
                animation: 150,
                handle: '.cursor-grab',
                onEnd: (evt) => {
                    const orders = [];
                    Array.from(listEl.children).forEach((child, index) => {
                        orders.push({ id: child.dataset.id, order_index: index });
                    });
                    axios.patch('/tasks/reorder', { orders })
                        .then(() => console.log('Order updated'))
                        .catch(error => console.error('Error reordering:', error));
                }
            });
        }
    }
}));

// Register with Alpine (legacy support)
Alpine.data('taskManager', taskManager);

// Load editor asynchronously to prevent blocking Alpine
import('./task-editor').then(() => {
    console.log('Task Editor imported asynchronously');
}).catch(err => {
    console.error('Failed to import Task Editor:', err);
});

// Helper to convert object to FormData
function objectToFormData(obj, form = null, namespace = '') {
    const fd = form || new FormData();
    let formKey;

    for (const property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (namespace) {
                formKey = namespace + '[' + property + ']';
            } else {
                formKey = property;
            }

            // if the property is an object, but not a File, use recursivity.
            if (typeof obj[property] === 'object' && !(obj[property] instanceof File) && obj[property] !== null) {
                objectToFormData(obj[property], fd, formKey);
            } else {
                // Handle different value types
                let value;
                if (obj[property] === null || obj[property] === undefined) {
                    value = '';
                } else if (typeof obj[property] === 'boolean') {
                    // Convert boolean to 1 or 0 for Laravel validation
                    value = obj[property] ? '1' : '0';
                } else {
                    value = obj[property];
                }
                fd.append(formKey, value);
            }
        }
    }
    return fd;
}

window.createTask = (taskData) => {
    console.log('🚀 createTask called with data:', taskData);

    // Check if we have files to upload (in supporting_files)
    let hasFiles = false;
    if (taskData.supporting_files && taskData.supporting_files.length > 0) {
        hasFiles = taskData.supporting_files.some(f => f.raw_file instanceof File);
    }

    let payload = taskData;
    if (hasFiles) {
        payload = objectToFormData(taskData);
    }

    axios.post('/tasks', payload)
        .then(response => {
            window.location.reload();
        })
        .catch(error => {
            console.error('Create Task Error:', error);
            console.error('Error Response:', error.response);
            console.error('Error Data:', error.response?.data);
            console.error('Validation Errors:', error.response?.data?.errors);
            console.error('Error Message:', error.response?.data?.message);
            console.error('Error Status:', error.response?.status);
            console.error('Error Headers:', error.response?.headers);
            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Error creating task', type: 'error' } }));
        });
};

window.updateTask = (id, data) => {
    // Check if we have files to upload
    let hasFiles = false;
    if (data.supporting_files && data.supporting_files.length > 0) {
        hasFiles = data.supporting_files.some(f => f.raw_file instanceof File);
    }

    if (hasFiles) {
        let payload = objectToFormData(data);
        payload.append('_method', 'PATCH'); // Spoof PATCH for FormData

        axios.post(`/tasks/${id}`, payload) // Browser sets Content-Type with boundary
            .then(response => {
                window.location.reload();
            })
            .catch(error => {
                console.error('Update Task Error (with files):', error);
                console.error('Error Response:', error.response);
                console.error('Error Data:', error.response?.data);
                console.error('Validation Errors:', error.response?.data?.errors);
                console.error('Error Message:', error.response?.data?.message);
                console.error('Error Status:', error.response?.status);
                window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Error updating task', type: 'error' } }));
            });
    } else {
        axios.patch(`/tasks/${id}`, data)
            .then(response => {
                window.location.reload();
            })
            .catch(error => {
                console.error('Update Task Error (no files):', error);
                console.error('Error Response:', error.response);
                console.error('Error Data:', error.response?.data);
                window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Error updating task', type: 'error' } }));
            });
    }
};

window.deleteTask = (id) => {
    if (!confirm('Are you sure you want to delete this task? This action cannot be undone.')) {
        return;
    }

    axios.delete(`/tasks/${id}`)
        .then(response => {
            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Task deleted successfully', type: 'success' } }));
            window.location.reload();
        })
        .catch(error => {
            console.error('Delete Task Error:', error);
            console.error('Error Response:', error.response);
            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Error deleting task', type: 'error' } }));
        });
};

window.toggleComplete = (id, status) => {
    axios.patch(`/tasks/${id}`, { is_completed: status })
        .then(response => {
            window.location.reload();
        })
        .catch(error => {
            window.dispatchEvent(new CustomEvent('notify', { detail: { message: 'Error updating task', type: 'error' } }));
        });
};

window.openEditModal = (task) => {
    window.dispatchEvent(new CustomEvent('open-edit-task-modal', { detail: task }));
};

// Listen for events from modal
window.addEventListener('create-task', event => {
    window.createTask(event.detail);
});

window.addEventListener('update-task', event => {
    window.updateTask(event.detail.id, event.detail.data);
});

// Confirm all functions loaded
console.log('✅ TaskWeb: All global functions loaded', {
    taskManager: typeof window.taskManager,
    createTask: typeof window.createTask,
    updateTask: typeof window.updateTask,
    deleteTask: typeof window.deleteTask,
    toggleComplete: typeof window.toggleComplete,
    openEditModal: typeof window.openEditModal,
    Alpine: typeof window.Alpine
});

window.Alpine = Alpine;
Alpine.start();
