<script lang="ts">
import { getProxyConfig, loadAppConfig, updateProxyConfig } from '$lib/utils/app-config';
import {
  createDebouncedTrigger,
  createSaveFeedbackController,
  type SaveFeedbackState,
} from '$lib/utils/form-save';
import { onDestroy, onMount } from 'svelte';

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

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

onMount(async () => {
  try {
    const config = await loadAppConfig();
    proxyPassword = getProxyConfig(config).password ?? '';
  } catch (error) {
    console.error('Failed to load proxy password:', error);
  }
});

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

async function saveProxyPassword(value: string) {
  const nextPassword = value.trim();

  try {
    await updateProxyConfig((current) => ({
      ...current,
      password: nextPassword || null,
    }));
    feedback.markUpdated();
  } catch (error) {
    console.error('Failed to save proxy password:', error);
    feedback.markNotUpdated();
  }
}

const saveLater = createDebouncedTrigger(() => {
  void saveProxyPassword(proxyPassword);
}, 800);

function savePasswordDelayed() {
  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]">Password</span>
  <input
    type="password"
    bind:value={proxyPassword}
    oninput={savePasswordDelayed}
    class="min-w-[20em] focus:outline-none" />
</label>
