<script setup lang="ts">
import type { PortfolioSummary } from '~~/types'

const { data, refresh } = await useFetch<{ portfolios: PortfolioSummary[] }>('/api/portfolios')
const toast = useToast()

const portfolios = computed(() => data.value?.portfolios ?? [])
const creating = ref(false)
const newName = ref('')
const showCreate = ref(false)

const dateFmt = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium', timeStyle: 'short' })

async function create() {
  creating.value = true
  try {
    const p = await $fetch<{ id: string }>('/api/portfolios', {
      method: 'POST',
      body: { name: newName.value },
    })
    navigateTo(`/portfolios/${p.id}`)
  } finally {
    creating.value = false
  }
}

async function duplicate(id: string) {
  await $fetch(`/api/portfolios/${id}/duplicate`, { method: 'POST' })
  await refresh()
  toast.add({ title: 'Portfolio dupliqué', color: 'success' })
}

async function remove(id: string, name: string) {
  if (!confirm(`Supprimer le portfolio « ${name} » ? Cette action est définitive.`)) return
  await $fetch(`/api/portfolios/${id}`, { method: 'DELETE' })
  await refresh()
  toast.add({ title: 'Portfolio supprimé', color: 'neutral' })
}

const downloading = ref<string | null>(null)

/**
 * Télécharge le PDF : direct s'il est à jour, sinon (jamais généré ou modifié
 * depuis) on le génère puis on le télécharge.
 */
async function downloadPdf(p: PortfolioSummary) {
  if (p.pdfCurrent && p.exportFileName) {
    window.open(`/api/exports/${encodeURIComponent(p.exportFileName)}`, '_blank')
    return
  }
  downloading.value = p.id
  try {
    const result = await $fetch<{ fileName: string, downloadUrl: string }>(`/api/portfolios/${p.id}/generate`, {
      method: 'POST',
      body: {},
      timeout: 300_000,
    })
    toast.add({ title: 'PDF généré', description: result.fileName, color: 'success' })
    window.open(result.downloadUrl, '_blank')
    await refresh() // rafraîchit pdfCurrent / exportFileName sur la carte
  } catch {
    toast.add({ title: 'Échec de la génération', color: 'error' })
  } finally {
    downloading.value = null
  }
}

async function copyPublicLink(id: string) {
  const url = `${window.location.origin}/view/${id}`
  if (await copyToClipboard(url)) {
    toast.add({ title: 'Lien public copié', color: 'success' })
  } else {
    toast.add({ title: 'Copie impossible', description: url, color: 'error' })
  }
}

const sharing = ref<string | null>(null)

/** Active le lien public (fige le contenu) puis copie l'URL. */
async function enableShare(id: string) {
  sharing.value = id
  try {
    await $fetch(`/api/portfolios/${id}/share`, { method: 'POST', body: {} })
    await refresh()
    await copyPublicLink(id)
  } catch {
    toast.add({ title: 'Échec de la génération du lien', color: 'error' })
  } finally {
    sharing.value = null
  }
}
</script>

<template>
  <div class="flex h-screen">
    <!-- Colonne gauche : header logo (fond + bordure), colonne transparente -->
    <aside class="w-60 shrink-0">
      <BrandBar />
    </aside>

    <!-- Grille des portfolios, pleine hauteur -->
    <main class="flex min-w-0 flex-1 flex-col overflow-hidden">
      <div class="flex h-14 items-center justify-end gap-2 border-b border-neutral-200 bg-white px-6 dark:border-neutral-800 dark:bg-neutral-900">
        <RefreshButton />
        <UButton icon="i-lucide-plus" size="sm" label="Nouveau portfolio" @click="showCreate = true" />
      </div>

      <div class="flex-1 overflow-auto p-6">
        <div v-if="!portfolios.length" class="rounded-lg border border-dashed border-neutral-300 p-16 text-center text-neutral-500 dark:border-neutral-700">
          Aucun portfolio pour l'instant — créez-en un pour composer votre premier PDF.
        </div>

        <div v-else class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          <UCard v-for="p in portfolios" :key="p.id">
        <div class="flex items-start justify-between gap-2">
          <div>
            <NuxtLink :to="`/portfolios/${p.id}`" class="font-semibold text-[var(--fl-ink)] hover:underline dark:text-white">
              {{ p.name }}
            </NuxtLink>
            <p class="mt-1 text-xs text-neutral-500">
              {{ p.pageCount }} page{{ p.pageCount > 1 ? 's' : '' }} · modifié le {{ dateFmt.format(new Date(p.updatedAt)) }}
            </p>
          </div>
          <div class="flex shrink-0 items-center gap-1.5">
            <UBadge v-if="p.publicShare" color="info" variant="subtle" size="sm">Public</UBadge>
            <UBadge v-if="p.hasPdf" color="success" variant="subtle" size="sm">PDF</UBadge>
          </div>
        </div>
        <div class="mt-4 space-y-2">
          <div class="flex gap-2">
            <UButton :to="`/portfolios/${p.id}`" class="flex-1 justify-center" size="sm" variant="soft" icon="i-lucide-pencil" label="Ouvrir" />
            <UButton class="flex-1 justify-center" size="sm" variant="ghost" color="neutral" icon="i-lucide-copy" label="Dupliquer" @click="duplicate(p.id)" />
          </div>
          <div class="flex gap-2">
            <UButton
              class="flex-1 justify-center"
              size="sm"
              variant="ghost"
              color="neutral"
              :icon="p.pdfCurrent ? 'i-lucide-download' : 'i-lucide-file-down'"
              :label="p.pdfCurrent ? 'Télécharger' : (p.hasPdf ? 'Régénérer' : 'Générer')"
              :loading="downloading === p.id"
              @click="downloadPdf(p)"
            />
            <UButton
              class="flex-1 justify-center"
              size="sm"
              variant="ghost"
              color="neutral"
              :icon="p.publicShare ? 'i-lucide-link' : 'i-lucide-link-2'"
              :label="p.publicShare ? 'Copier le lien' : 'Générer le lien'"
              :loading="sharing === p.id"
              @click="p.publicShare ? copyPublicLink(p.id) : enableShare(p.id)"
            />
          </div>
          <UButton class="w-full justify-center" size="sm" variant="ghost" color="error" icon="i-lucide-trash-2" label="Supprimer" @click="remove(p.id, p.name)" />
        </div>
          </UCard>
        </div>
      </div>
    </main>

    <UModal v-model:open="showCreate" title="Nouveau portfolio">
      <template #body>
        <form class="space-y-4" @submit.prevent="create">
          <UInput v-model="newName" placeholder="Nom du portfolio (ex. Candidature Bagneux)" class="w-full" autofocus />
          <div class="flex justify-end gap-2">
            <UButton variant="ghost" color="neutral" label="Annuler" @click="showCreate = false" />
            <UButton type="submit" :loading="creating" label="Créer" />
          </div>
        </form>
      </template>
    </UModal>
  </div>
</template>
