<template>
  <section class="card flex flex-col gap-3">
    <h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
      <Plug :size="16" /> {{ t('gitconn.title') }}
    </h2>
    <p class="text-xs text-zinc-500">{{ t('gitconn.hint') }}</p>

    <!-- liste des connexions -->
    <ul v-if="store.connections.length" class="flex flex-col gap-1">
      <li v-for="c in store.connections" :key="c.id" class="card-inset flex flex-wrap items-center gap-2">
        <BaseBadge tone="sky">{{ c.service }}</BaseBadge>
        <span class="font-medium text-zinc-200">{{ c.label }}</span>
        <span class="text-xs text-zinc-500">{{ c.authType }}<template v-if="c.username"> · {{ c.username }}</template></span>
        <span v-if="c.hasSecret" class="font-mono text-xs text-zinc-600">••••{{ c.secretLast4 }}</span>
        <BaseBadge v-if="c.testResult" :tone="c.testResult === 'ok' ? 'emerald' : 'red'">{{ c.testResult }}</BaseBadge>
        <span class="ml-auto flex items-center gap-1">
          <BaseButton size="sm" variant="ghost" :loading="testingId === c.id" @click="onTest(c.id)">{{ t('gitconn.test') }}</BaseButton>
          <BaseButton v-if="confirmId === c.id" size="sm" variant="danger" @click="onDelete(c.id)">{{ t('common.confirm') }}</BaseButton>
          <BaseButton v-else size="sm" variant="ghost" :icon="Trash2" :aria-label="t('common.delete')" icon-only @click="confirmId = c.id" />
        </span>
      </li>
    </ul>
    <p v-else class="text-xs text-zinc-600">{{ t('gitconn.empty') }}</p>

    <!-- formulaire d'ajout -->
    <form v-if="adding" class="card-inset flex flex-col gap-2" @submit.prevent="onCreate">
      <div class="flex flex-wrap gap-2">
        <label class="flex flex-col gap-1 text-xs text-zinc-400">
          {{ t('gitconn.service') }}
          <select v-model="form.service" class="input">
            <option value="gitea">Gitea</option>
            <option value="gitlab">GitLab</option>
            <option value="github">GitHub</option>
          </select>
        </label>
        <label class="flex flex-col gap-1 text-xs text-zinc-400">
          {{ t('gitconn.authType') }}
          <select v-model="form.authType" class="input">
            <option value="pat">{{ t('gitconn.pat') }}</option>
            <option value="app_password">{{ t('gitconn.appPassword') }}</option>
          </select>
        </label>
        <label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
          {{ t('gitconn.label') }}
          <input v-model.trim="form.label" class="input" :placeholder="t('gitconn.labelPlaceholder')" required />
        </label>
      </div>
      <label v-if="form.service === 'gitea' || form.service === 'gitlab'" class="flex flex-col gap-1 text-xs text-zinc-400">
        {{ t('gitconn.baseUrl') }}<template v-if="form.service === 'gitea'"> *</template>
        <input v-model.trim="form.baseUrl" class="input font-mono" placeholder="https://git.example.com" :required="form.service === 'gitea'" />
      </label>
      <div class="flex flex-wrap gap-2">
        <label class="flex flex-col gap-1 text-xs text-zinc-400">
          {{ t('gitconn.username') }}
          <input v-model.trim="form.username" class="input" :placeholder="t('gitconn.usernamePlaceholder')" />
        </label>
        <label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
          {{ form.authType === 'pat' ? t('gitconn.token') : t('gitconn.password') }}
          <input v-model="form.secret" type="password" class="input font-mono" autocomplete="off" required />
        </label>
      </div>
      <p v-if="error" class="text-xs text-amber-400">{{ error }}</p>
      <div class="flex items-center gap-2">
        <BaseButton type="submit" variant="primary" size="sm" :loading="creating" :disabled="!canCreate">{{ t('gitconn.add') }}</BaseButton>
        <BaseButton type="button" size="sm" variant="ghost" @click="adding = false">{{ t('common.cancel') }}</BaseButton>
      </div>
    </form>
    <div v-else>
      <BaseButton size="sm" :icon="Plus" @click="openForm">{{ t('gitconn.addConnection') }}</BaseButton>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plug, Plus, Trash2 } from '@lucide/vue';
import type { GitAuthType, GitService } from '@arboretum/shared';
import { useGitConnectionsStore } from '../../stores/git-connections';
import { useToastsStore } from '../../stores/toasts';
import BaseButton from '../ui/BaseButton.vue';
import BaseBadge from '../ui/BaseBadge.vue';

const { t } = useI18n();
const store = useGitConnectionsStore();
const toasts = useToastsStore();

const adding = ref(false);
const creating = ref(false);
const error = ref<string | null>(null);
const testingId = ref<string | null>(null);
const confirmId = ref<string | null>(null);
const form = reactive({ service: 'gitea' as GitService, authType: 'pat' as GitAuthType, label: '', baseUrl: '', username: '', secret: '' });

const canCreate = computed(
  () => form.label.trim() !== '' && form.secret !== '' && (form.service !== 'gitea' || form.baseUrl.trim() !== ''),
);

onMounted(() => void store.fetchAll());

function openForm(): void {
  Object.assign(form, { service: 'gitea', authType: 'pat', label: '', baseUrl: '', username: '', secret: '' });
  error.value = null;
  adding.value = true;
}

async function onCreate(): Promise<void> {
  creating.value = true;
  error.value = null;
  try {
    await store.create({
      label: form.label.trim(),
      service: form.service,
      authType: form.authType,
      ...(form.baseUrl.trim() ? { baseUrl: form.baseUrl.trim() } : {}),
      ...(form.username.trim() ? { username: form.username.trim() } : {}),
      secret: form.secret,
    });
    adding.value = false;
    toasts.success(t('gitconn.added'));
  } catch (e) {
    error.value = e instanceof Error ? e.message : String(e);
  } finally {
    creating.value = false;
  }
}

async function onTest(id: string): Promise<void> {
  testingId.value = id;
  try {
    const res = await store.test(id);
    if (res.ok) toasts.success(t('gitconn.testOk', { user: res.user ?? '' }));
    else toasts.error(t('gitconn.testFailed', { error: res.error ?? '' }));
  } catch (e) {
    toasts.error(e);
  } finally {
    testingId.value = null;
  }
}

async function onDelete(id: string): Promise<void> {
  confirmId.value = null;
  try {
    await store.remove(id);
    toasts.success(t('gitconn.deleted'));
  } catch (e) {
    toasts.error(e);
  }
}
</script>
