const vscode = require('vscode');

class VigthoriaTodoProvider {
    constructor(extensionUri, context) {
        this.extensionUri = extensionUri;
        this.context = context;
        this.todos = context.globalState.get('vigthoria.todos', []);
        this.aiTaskPlans = context.globalState.get('vigthoria.aiTaskPlans', {});
        this.view = null;
    }

    resolveWebviewView(webviewView) {
        this.view = webviewView;
        webviewView.webview.options = { enableScripts: true };
        webviewView.webview.html = this._getHtml();

        webviewView.webview.onDidReceiveMessage((message) => {
            if (!message || !message.type) return;

            if (message.type === 'addTodo' && message.text) {
                this.addTodoFromExternal(message.text, message.priority || 'medium');
            }

            if (message.type === 'toggleTodo') {
                this._toggleTodo(message.id);
            }

            if (message.type === 'clearCompleted') {
                this._clearCompleted();
            }
        });

        this._postState();
    }

    addTodoFromExternal(text, priority = 'medium') {
        const todo = {
            id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
            text,
            priority,
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.todos.unshift(todo);
        this._persist();
        this._postState();
        return todo;
    }

    setAITaskPlan(mode, steps = []) {
        this.aiTaskPlans[mode] = steps.map((step, index) => ({
            id: `${mode}-${index}`,
            text: typeof step === 'string' ? step : step.text || step.title || `Step ${index + 1}`,
            status: step.status || 'pending'
        }));
        this._persist();
        this._postState();
    }

    updateTaskStatus(mode, stepIndex, status) {
        const plan = this.aiTaskPlans[mode];
        if (!Array.isArray(plan) || !plan[stepIndex]) return;
        plan[stepIndex].status = status;
        this._persist();
        this._postState();
    }

    completeAllAITasks(mode) {
        const plan = this.aiTaskPlans[mode];
        if (!Array.isArray(plan)) return;
        plan.forEach((task) => { task.status = 'completed'; });
        this._persist();
        this._postState();
    }

    _toggleTodo(id) {
        const todo = this.todos.find((item) => item.id === id);
        if (!todo) return;
        todo.completed = !todo.completed;
        this._persist();
        this._postState();
    }

    _clearCompleted() {
        this.todos = this.todos.filter((todo) => !todo.completed);
        this._persist();
        this._postState();
    }

    _persist() {
        this.context.globalState.update('vigthoria.todos', this.todos);
        this.context.globalState.update('vigthoria.aiTaskPlans', this.aiTaskPlans);
    }

    _postState() {
        if (!this.view) return;
        this.view.webview.postMessage({
            type: 'state',
            todos: this.todos,
            aiTaskPlans: this.aiTaskPlans
        });
    }

    _getHtml() {
        const nonce = Date.now().toString(36);
        return `<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 12px; }
        .row { display: flex; gap: 6px; margin-bottom: 12px; }
        input { flex: 1; background: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border); padding: 6px; }
        button { background: var(--vscode-button-background); color: var(--vscode-button-foreground); border: 0; padding: 6px 10px; cursor: pointer; }
        .item { display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--vscode-panel-border); }
        .done { opacity: .65; text-decoration: line-through; }
        .plan { margin-top: 16px; }
        .status { font-size: 11px; color: var(--vscode-descriptionForeground); margin-left: auto; }
    </style>
</head>
<body>
    <div class="row"><input id="newTodo" placeholder="Add task"><button id="add">Add</button></div>
    <div id="todos"></div>
    <button id="clear">Clear completed</button>
    <div id="plans" class="plan"></div>
    <script nonce="${nonce}">
        const vscode = acquireVsCodeApi();
        const todosEl = document.getElementById('todos');
        const plansEl = document.getElementById('plans');
        document.getElementById('add').addEventListener('click', () => {
            const input = document.getElementById('newTodo');
            if (input.value.trim()) vscode.postMessage({ type: 'addTodo', text: input.value.trim() });
            input.value = '';
        });
        document.getElementById('clear').addEventListener('click', () => vscode.postMessage({ type: 'clearCompleted' }));
        window.addEventListener('message', (event) => {
            const state = event.data || {};
            todosEl.innerHTML = (state.todos || []).map((todo) => '<div class="item"><input type="checkbox" data-id="' + todo.id + '" ' + (todo.completed ? 'checked' : '') + '><span class="' + (todo.completed ? 'done' : '') + '">' + escapeHtml(todo.text) + '</span><span class="status">' + todo.priority + '</span></div>').join('') || '<p>No tasks yet.</p>';
            todosEl.querySelectorAll('input[type="checkbox"]').forEach((box) => box.addEventListener('change', () => vscode.postMessage({ type: 'toggleTodo', id: box.dataset.id })));
            const plans = state.aiTaskPlans || {};
            plansEl.innerHTML = Object.keys(plans).map((mode) => '<h4>' + escapeHtml(mode) + '</h4>' + plans[mode].map((task) => '<div class="item"><span>' + escapeHtml(task.text) + '</span><span class="status">' + escapeHtml(task.status) + '</span></div>').join('')).join('');
        });
        function escapeHtml(value) { return String(value).replace(/[&<>"']/g, (char) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char])); }
    </script>
</body>
</html>`;
    }
}

module.exports = { VigthoriaTodoProvider };
