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

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

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

  function getTypeColor(type) {
    if (!type) return "bg-gray-100 text-gray-700";
    const t = type.toLowerCase();
    if (t.includes("date") || t.includes("time")) return "bg-green-100 text-green-700";
    if (t.includes("string") || t.includes("text") || t.includes("varchar") || t.includes("char")) return "bg-purple-100 text-purple-700";
    if (t.includes("int") || t.includes("bigint") || t.includes("smallint")) return "bg-blue-100 text-blue-700";
    if (t.includes("float") || t.includes("double") || t.includes("decimal") || t.includes("numeric")) return "bg-orange-100 text-orange-700";
    if (t.includes("bool")) return "bg-yellow-100 text-yellow-700";
    return "bg-gray-100 text-gray-700";
  }

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

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

  async function saveEdit(col) {
    isSaving = true;
    editError = null;
    try {
      const result = await api.requestApi(
        `/datasets/${datasetId}/columns/${col.id}/description?env_id=${envId}`,
        "PUT",
        { description: editValue }
      );
      col.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?.table_name ?? 'Column'}</th>
        <th class="py-2 px-3 w-20">{$t.dashboard?.type ?? 'Type'}</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 columns.length === 0}
        <tr><td colspan="4" class="py-4 text-center text-gray-400">{$t.datasets?.detail_empty ?? 'No data'}</td></tr>
      {:else}
        {#each columns as col (col.id)}
          <tr class="border-b border-gray-100 hover:bg-gray-50 {editingRowId && editingRowId !== col.id ? 'opacity-50' : ''}">
            <td class="py-2 px-3">
              {#if col.verbose_name}
                <span class="font-medium">{col.verbose_name}</span>
              {:else}
                <span class="italic text-gray-600">{col.name}</span>
              {/if}
            </td>
            <td class="py-2 px-3">
              <span class="inline-block px-1.5 py-0.5 rounded text-xs font-medium {getTypeColor(col.type)}">
                {col.type ?? '—'}
              </span>
            </td>
            <td class="py-2 px-3">
              {#if editingRowId === col.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(col)}
                      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 col.description}
                <span class="text-gray-700">{col.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 !== col.id}
                <button
                  class="text-gray-400 hover:text-primary text-sm"
                  onclick={() => startEdit(col)}
                  aria-label={$t.datasets?.add_description ?? 'Edit'}
                >✏️</button>
              {/if}
            </td>
          </tr>
        {/each}
      {/if}
    </tbody>
  </table>
</div>
<!-- #endregion ColumnsTable -->