<script>
    import { plugins as pluginsStore, selectedPlugin, selectedTask } from '../lib/stores.js';
    import TaskRunner from '../components/TaskRunner.svelte';
    import DynamicForm from '../components/DynamicForm.svelte';
    import { api } from '../lib/api.js';
    import { get } from 'svelte/store';

    /** @type {import('./$types').PageData} */
    export let data;

    // Sync store with loaded data if needed, or just use data.plugins directly
    $: if (data.plugins) {
        pluginsStore.set(data.plugins);
    }

    function selectPlugin(plugin) {
        console.log(`[Dashboard][Action] Selecting plugin: ${plugin.id}`);
        selectedPlugin.set(plugin);
    }

    async function handleFormSubmit(event) {
        console.log("[App.handleFormSubmit][Action] Handling form submission for task creation.");
        const params = event.detail;
        try {
            const plugin = get(selectedPlugin);
            const task = await api.createTask(plugin.id, params);
            selectedTask.set(task);
            selectedPlugin.set(null);
            console.log(`[App.handleFormSubmit][Coherence:OK] Task created id=${task.id}`);
        } catch (error) {
            console.error(`[App.handleFormSubmit][Coherence:Failed] Task creation failed error=${error}`);
        }
    }
</script>

<div class="container mx-auto p-4">
    {#if $selectedTask}
        <TaskRunner />
        <button on:click={() => selectedTask.set(null)} class="mt-4 bg-blue-500 text-white p-2 rounded">
            Back to Task List
        </button>
    {:else if $selectedPlugin}
        <h2 class="text-2xl font-bold mb-4">{$selectedPlugin.name}</h2>
        <DynamicForm schema={$selectedPlugin.schema} on:submit={handleFormSubmit} />
        <button on:click={() => selectedPlugin.set(null)} class="mt-4 bg-gray-500 text-white p-2 rounded">
            Back to Dashboard
        </button>
    {:else}
        <h1 class="text-2xl font-bold mb-4">Available Tools</h1>
        {#if data.error}
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                {data.error}
            </div>
        {/if}
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {#each data.plugins as plugin}
                <div 
                    class="border rounded-lg p-4 cursor-pointer hover:bg-gray-100"
                    on:click={() => selectPlugin(plugin)}
                    role="button"
                    tabindex="0"
                    on:keydown={(e) => e.key === 'Enter' && selectPlugin(plugin)}
                >
                    <h2 class="text-xl font-semibold">{plugin.name}</h2>
                    <p class="text-gray-600">{plugin.description}</p>
                    <span class="text-sm text-gray-400">v{plugin.version}</span>
                </div>
            {/each}
        </div>
    {/if}
</div>
