<script lang="ts">
import { activeDatasetMeta, updateActiveDatasetMeta } from '$lib/stores/dataset';
import {
  createDebouncedTrigger,
  createSaveFeedbackController,
  type SaveFeedbackState,
} from '$lib/utils/form-save';
import { onDestroy, onMount } from 'svelte';
import { get } from 'svelte/store';

let name = $state('');
let saveFeedback = $state<SaveFeedbackState>('idle');

const feedback = createSaveFeedbackController((state) => {
  saveFeedback = state;
});

onMount(() => {
  name = get(activeDatasetMeta)?.name ?? '';
});

onDestroy(() => {
  saveLater.cancel();
  feedback.dispose();
});

async function saveDatasetName(value: string) {
  const nextName = value.trim();

  if (!nextName) {
    feedback.markNotUpdated();
    return;
  }

  try {
    await updateActiveDatasetMeta({ name: nextName });
    feedback.markUpdated();
  } catch (error) {
    console.error('Failed to save dataset name:', error);
    feedback.markNotUpdated();
  }
}

const saveLater = createDebouncedTrigger(() => {
  void saveDatasetName(name);
}, 3000);

function saveNameDelayed() {
  saveLater.trigger();
}
</script>

<label
  class={[
    'input w-fit in-focus-within:outline-none transition-colors duration-300 ease-out',
    saveFeedback === 'updated' && 'border-green-500',
    saveFeedback === 'not-updated' && 'border-red-500',
  ]}>
  <span class="label min-w-[10em]">Dataset Name</span>
  <input
    type="text"
    bind:value={name}
    oninput={saveNameDelayed}
    class="min-w-[20em] focus:outline-none" />
</label>
