<!-- [DEF:TaskManagementPage:Component] -->
<!--
@SEMANTICS: tasks, management, history, logs
@PURPOSE: Page for managing and monitoring tasks.
@LAYER: Page
@RELATION: USES -> TaskList
@RELATION: USES -> TaskLogViewer
-->
<script>
  import { onMount, onDestroy } from 'svelte';
  import { getTasks, createTask, getEnvironmentsList } from '../../lib/api';
  import { addToast } from '../../lib/toasts';
  import TaskList from '../../components/TaskList.svelte';
  import TaskLogViewer from '../../components/TaskLogViewer.svelte';
  import { t } from '$lib/i18n';
  import { Button, Card, PageHeader, Select } from '$lib/ui';

  let tasks = [];
  let environments = [];
  let loading = true;
  let selectedTaskId = null;
  let pollInterval;
  let showBackupModal = false;
  let selectedEnvId = '';

  // [DEF:loadInitialData:Function]
  /**
   * @purpose Loads tasks and environments on page initialization.
   * @pre API must be reachable.
   * @post tasks and environments variables are populated.
   */
  async function loadInitialData() {
    console.log("[loadInitialData][Action] Loading initial tasks and environments");
    try {
      loading = true;
      const [tasksData, envsData] = await Promise.all([
        getTasks(),
        getEnvironmentsList()
      ]);
      tasks = tasksData;
      environments = envsData;
      console.log(`[loadInitialData][Coherence:OK] Data loaded context={{'tasks': ${tasks.length}, 'envs': ${environments.length}}}`);
    } catch (error) {
      console.error(`[loadInitialData][Coherence:Failed] Failed to load tasks data context={{'error': '${error.message}'}}`);
    } finally {
      loading = false;
    }
  }
  // [/DEF:loadInitialData:Function]

  // [DEF:refreshTasks:Function]
  /**
   * @purpose Periodically refreshes the task list.
   * @pre API must be reachable.
   * @post tasks variable is updated if data is valid.
   */
  async function refreshTasks() {
    try {
      const data = await getTasks();
      // Ensure we don't try to parse HTML as JSON if the route returns 404
      if (Array.isArray(data)) {
        tasks = data;
      }
    } catch (error) {
      console.error(`[refreshTasks][Coherence:Failed] Failed to refresh tasks context={{'error': '${error.message}'}}`);
    }
  }
  // [/DEF:refreshTasks:Function]

  // [DEF:handleSelectTask:Function]
  /**
   * @purpose Updates the selected task ID when a task is clicked.
   * @pre event.detail.id must be provided.
   * @post selectedTaskId is updated.
   */
  function handleSelectTask(event) {
    selectedTaskId = event.detail.id;
    console.log(`[handleSelectTask][Action] Task selected context={{'taskId': '${selectedTaskId}'}}`);
  }
  // [/DEF:handleSelectTask:Function]

  // [DEF:handleRunBackup:Function]
  /**
   * @purpose Triggers a manual backup task for the selected environment.
   * @pre selectedEnvId must not be empty.
   * @post Backup task is created and task list is refreshed.
   */
  async function handleRunBackup() {
    if (!selectedEnvId) {
      addToast('Please select an environment', 'error');
      return;
    }

    console.log(`[handleRunBackup][Action] Starting backup for env context={{'envId': '${selectedEnvId}'}}`);
    try {
      const task = await createTask('superset-backup', { environment_id: selectedEnvId });
      addToast('Backup task started', 'success');
      showBackupModal = false;
      selectedTaskId = task.id;
      await refreshTasks();
      console.log(`[handleRunBackup][Coherence:OK] Backup task created context={{'taskId': '${task.id}'}}`);
    } catch (error) {
      console.error(`[handleRunBackup][Coherence:Failed] Failed to start backup context={{'error': '${error.message}'}}`);
    }
  }
  // [/DEF:handleRunBackup:Function]

  onMount(() => {
    loadInitialData();
    pollInterval = setInterval(refreshTasks, 3000);
  });

  onDestroy(() => {
    if (pollInterval) clearInterval(pollInterval);
  });
</script>

<div class="container mx-auto p-4 max-w-6xl">
  <PageHeader title={$t.tasks.management} />

  <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-1">
      <h2 class="text-lg font-semibold mb-3 text-gray-700">{$t.tasks.recent}</h2>
      <TaskList {tasks} {loading} on:select={handleSelectTask} />
    </div>

    <div class="lg:col-span-2">
      <h2 class="text-lg font-semibold mb-3 text-gray-700">{$t.tasks.details_logs}</h2>
      {#if selectedTaskId}
        <Card padding="none">
          <div class="h-[600px] flex flex-col overflow-hidden rounded-lg">
            <TaskLogViewer
              taskId={selectedTaskId}
              taskStatus={tasks.find(t => t.id === selectedTaskId)?.status}
              inline={true}
            />
          </div>
        </Card>
      {:else}
        <div class="bg-gray-50 border-2 border-dashed border-gray-100 rounded-lg h-[600px] flex items-center justify-center text-gray-400">
          <p>{$t.tasks.select_task}</p>
        </div>
      {/if}
    </div>
  </div>
</div>

{#if showBackupModal}
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-gray-900/50 backdrop-blur-sm p-4">
    <div class="w-full max-w-md">
      <Card title={$t.tasks.manual_backup}>
        <div class="space-y-6">
          <Select
            label={$t.tasks.target_env}
            bind:value={selectedEnvId}
            options={[
              { value: '', label: $t.tasks.select_env },
              ...environments.map(e => ({ value: e.id, label: e.name }))
            ]}
          />
          
          <div class="flex justify-end gap-3 pt-2">
            <Button variant="secondary" on:click={() => showBackupModal = false}>
              {$t.common.cancel}
            </Button>
            <Button variant="primary" on:click={handleRunBackup}>
              Start Backup
            </Button>
          </div>
        </div>
      </Card>
    </div>
  </div>
{/if}

<!-- [/DEF:TaskManagementPage:Component] -->