<!-- #region MetricsTable [C:4] [TYPE Component] [SEMANTICS ui,dataset,metrics,inline-edit] -->
<!-- @BRIEF Table of dataset metrics with expression, description, and inline-edit capability. -->
<!-- @LAYER UI -->
<!-- @RELATION CALLS -> [EXT:frontend:api_module] -->
<!-- @UX_STATE Display -> All rows in read mode with expression shown under name. -->
<!-- @UX_STATE Editing -> One row in edit mode. -->
<!-- @UX_REACTIVITY Props -> metrics, datasetId -->
<script lang="ts">
  import { t } from "$lib/i18n/index.svelte.js";
  import { api } from "$lib/api.js";

  let { metrics = [], datasetId, envId } = $props();

  let editingRowId = $state(null);
  let editValue = $state("");
  let editError = $state(null);
  let isSaving = $state(false);

  function startEdit(metric) {
    editingRowId = metric.id;
    editValue = metric.description ?? "";
    editError = null;
  }

  function cancelEdit() {
    editingRowId = null;
    editValue = "";
    editError = null;
  }

  async function saveEdit(metric) {
    isSaving = true;
    editError = null;
    try {
      const result = await api.requestApi(
        `/datasets/${datasetId}/metrics/${metric.id}/description?env_id=${envId}`,
        "PUT",
        { description: editValue }
      );
      metric.description = result.description;
      editingRowId = null;
    } catch (e) {
      editError = e.message || "Failed to save";
    } finally {
      isSaving = false;
    }
  }
</script>

<div class="overflow-x-auto">
  <table class="w-full text-sm">
    <thead>
      <tr class="border-b border-gray-200 text-left text-xs font-medium text-gray-500 uppercase">
        <th class="py-2 px-3 w-1/3">{$t.datasets?.metrics ?? 'Metric'}</th>
        <th class="py-2 px-3">{$t.dashboard?.description ?? 'Description'}</th>
        <th class="py-2 px-3 w-16"></th>
      </tr>
    </thead>
    <tbody>
      {#if metrics.length === 0}
        <tr><td colspan="3" class="py-4 text-center text-gray-400">{$t.datasets?.detail_empty ?? 'No data'}</td></tr>
      {:else}
        {#each metrics as metric (metric.id)}
          <tr class="border-b border-gray-100 hover:bg-gray-50 {editingRowId && editingRowId !== metric.id ? 'opacity-50' : ''}">
            <td class="py-2 px-3">
              {#if metric.verbose_name}
                <span class="font-medium">{metric.verbose_name}</span>
              {:else}
                <span class="italic text-gray-600">{metric.metric_name}</span>
              {/if}
              {#if !metric.description && metric.expression}
                <div class="text-xs text-gray-400 font-mono mt-0.5">{metric.expression}</div>
              {/if}
            </td>
            <td class="py-2 px-3">
              {#if editingRowId === metric.id}
                <div class="flex flex-col gap-1">
                  <textarea
                    class="w-full border rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 {editError ? 'border-red-400' : 'border-gray-300'}"
                    rows="2"
                    maxlength="2000"
                    bind:value={editValue}
                    aria-label="Description"
                  ></textarea>
                  {#if editError}
                    <span class="text-xs text-red-600" role="alert" aria-live="assertive">{editError}</span>
                  {/if}
                  <div class="flex gap-1">
                    <button
                      class="px-2 py-0.5 text-xs bg-primary text-white rounded hover:bg-primary-hover disabled:opacity-50"
                      onclick={() => saveEdit(metric)}
                      disabled={isSaving}
                    >{isSaving ? '...' : ($t.datasets?.save_description ?? 'Save')}</button>
                    <button
                      class="px-2 py-0.5 text-xs border border-gray-300 rounded hover:bg-gray-100"
                      onclick={cancelEdit}
                    >{$t.common?.cancel ?? 'Cancel'}</button>
                  </div>
                </div>
              {:else if metric.description}
                <span class="text-gray-700">{metric.description}</span>
              {:else}
                <span class="text-gray-400 italic">{'✏️ ' + ($t.datasets?.add_description ?? 'Add description')}</span>
              {/if}
            </td>
            <td class="py-2 px-3">
              {#if editingRowId !== metric.id}
                <button
                  class="text-gray-400 hover:text-primary text-sm"
                  onclick={() => startEdit(metric)}
                  aria-label={$t.datasets?.add_description ?? 'Edit'}
                >✏️</button>
              {/if}
            </td>
          </tr>
        {/each}
      {/if}
    </tbody>
  </table>
</div>
<!-- #endregion MetricsTable -->