<template>
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" @click.self="emit('close')">
    <div class="flex max-h-[90vh] w-full max-w-lg flex-col gap-3 overflow-y-auto rounded-lg border border-zinc-800 bg-zinc-900 p-4">
      <header class="flex items-center gap-2">
        <h2 class="font-semibold text-zinc-100">{{ t('clone.title') }}</h2>
        <button class="btn ml-auto text-xs" @click="emit('close')">{{ t('common.cancel') }}</button>
      </header>

      <!-- aucune connexion → renvoyer vers les réglages -->
      <p v-if="conn.connections.length === 0" class="text-sm text-zinc-400">
        {{ t('clone.noCredential') }}
        <RouterLink :to="{ name: 'settings' }" class="text-emerald-400 hover:underline" @click="emit('close')">{{ t('clone.goSettings') }}</RouterLink>
      </p>

      <template v-else-if="!operationId">
        <label class="flex flex-col gap-1 text-xs text-zinc-400">
          {{ t('clone.credential') }}
          <select v-model="credentialId" class="input" @change="loadRepos(1)">
            <option v-for="c in conn.connections" :key="c.id" :value="c.id">{{ c.label }} ({{ c.service }})</option>
          </select>
        </label>

        <div class="flex items-end gap-2">
          <label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
            {{ t('clone.search') }}
            <input v-model.trim="search" class="input" :placeholder="t('clone.searchPlaceholder')" @keyup.enter="loadRepos(1)" />
          </label>
          <BaseButton size="sm" :icon="RefreshCw" :loading="loadingRepos" @click="loadRepos(1)">{{ t('common.refresh') }}</BaseButton>
        </div>

        <p v-if="reposError" class="text-xs text-amber-400">{{ reposError }}</p>
        <ul class="flex max-h-52 flex-col gap-0.5 overflow-y-auto">
          <li v-for="r in repos" :key="r.fullName">
            <button
              type="button"
              class="flex w-full items-center gap-2 rounded px-2 py-1 text-left text-sm hover:bg-zinc-800"
              :class="selected?.fullName === r.fullName ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-300'"
              @click="select(r)"
            >
              <span class="min-w-0 flex-1 truncate font-mono">{{ r.fullName }}</span>
              <BaseBadge v-if="r.private" tone="zinc">{{ t('clone.private') }}</BaseBadge>
            </button>
          </li>
          <li v-if="!loadingRepos && repos.length === 0" class="px-2 py-1 text-xs text-zinc-600">{{ t('clone.noRepos') }}</li>
        </ul>
        <div v-if="nextPage" class="flex justify-center">
          <BaseButton size="sm" variant="ghost" :loading="loadingRepos" @click="loadRepos(nextPage)">{{ t('clone.more') }}</BaseButton>
        </div>

        <label class="flex flex-col gap-1 text-xs text-zinc-400">
          {{ t('clone.dest') }}
          <input v-model.trim="dest" class="input font-mono" :placeholder="t('clone.destPlaceholder')" />
          <span class="text-xs text-zinc-600">{{ t('clone.destHint') }}</span>
        </label>

        <p v-if="error" class="text-xs text-amber-400">{{ error }}</p>
        <div>
          <BaseButton variant="primary" :icon="Download" :loading="starting" :disabled="!canClone" @click="onClone">{{ t('clone.clone') }}</BaseButton>
        </div>
      </template>

      <!-- progression -->
      <template v-else>
        <p class="text-sm text-zinc-300">{{ progressLabel }}</p>
        <div class="h-2 w-full overflow-hidden rounded bg-zinc-800">
          <div class="h-full bg-emerald-500 transition-all" :style="{ width: `${op?.progress ?? 0}%` }" />
        </div>
        <p v-if="op?.state === 'error'" class="text-xs text-rose-400">{{ op.error }}</p>
        <div v-if="op?.state === 'error'" class="flex gap-2">
          <BaseButton size="sm" variant="ghost" @click="operationId = null">{{ t('clone.back') }}</BaseButton>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Download, RefreshCw } from '@lucide/vue';
import type { RemoteRepoSummary } from '@arboretum/shared';
import { useGitConnectionsStore } from '../stores/git-connections';
import { useCloneStore } from '../stores/clone';
import { useSettingsStore } from '../stores/settings';
import { useToastsStore } from '../stores/toasts';
import BaseButton from './ui/BaseButton.vue';
import BaseBadge from './ui/BaseBadge.vue';

const emit = defineEmits<{ close: [] }>();
const { t } = useI18n();
const router = useRouter();
const conn = useGitConnectionsStore();
const cloneStore = useCloneStore();
const settings = useSettingsStore();
const toasts = useToastsStore();

const credentialId = ref('');
const search = ref('');
const repos = ref<RemoteRepoSummary[]>([]);
const nextPage = ref<number | null>(null);
const loadingRepos = ref(false);
const reposError = ref<string | null>(null);
const selected = ref<RemoteRepoSummary | null>(null);
const dest = ref('');
const error = ref<string | null>(null);
const starting = ref(false);
const operationId = ref<string | null>(null);

const op = computed(() => (operationId.value ? cloneStore.get(operationId.value) ?? null : null));
const scanRoot = computed(() => settings.scanRoots[0] ?? '');
const canClone = computed(() => !!credentialId.value && !!selected.value && dest.value.trim() !== '');
const progressLabel = computed(() => {
  if (!op.value) return t('clone.starting');
  if (op.value.state === 'done') return t('clone.done');
  if (op.value.state === 'error') return t('clone.failed');
  return op.value.phase ? `${op.value.phase}… ${op.value.progress ?? 0}%` : t('clone.cloning');
});

onMounted(async () => {
  if (!settings.loaded) await settings.fetch();
  if (conn.connections.length === 0) await conn.fetchAll();
  const first = conn.connections[0];
  if (first) {
    credentialId.value = first.id;
    await loadRepos(1);
  }
});

async function loadRepos(page: number): Promise<void> {
  if (!credentialId.value) return;
  loadingRepos.value = true;
  reposError.value = null;
  try {
    const res = await conn.listRemoteRepos(credentialId.value, page, search.value || undefined);
    repos.value = page === 1 ? res.repos : [...repos.value, ...res.repos];
    nextPage.value = res.nextPage;
  } catch (e) {
    reposError.value = e instanceof Error ? e.message : String(e);
  } finally {
    loadingRepos.value = false;
  }
}

function select(r: RemoteRepoSummary): void {
  selected.value = r;
  const name = r.fullName.split('/').pop() ?? r.fullName;
  dest.value = scanRoot.value ? `${scanRoot.value}/${name}` : '';
}

async function onClone(): Promise<void> {
  if (!selected.value) return;
  starting.value = true;
  error.value = null;
  try {
    operationId.value = await cloneStore.clone({ credentialId: credentialId.value, remoteUrl: selected.value.cloneUrl, dest: dest.value.trim() });
  } catch (e) {
    error.value = e instanceof Error ? e.message : String(e);
    operationId.value = null;
  } finally {
    starting.value = false;
  }
}

// À la fin du clone : toast + redirection vers le tableau de bord (le repo y apparaît).
watch(op, (o) => {
  if (o?.state === 'done') {
    toasts.success(t('clone.done'));
    emit('close');
    void router.push({ name: 'dashboard' });
  }
});
</script>
