<script setup lang="ts">
import { computed, ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { breakpointsTailwind, useDebounce } from '@vueuse/core'
import EstudiosTypensenseDetail from '~/components/estudiosTypensense/EstudiosTypensenseDetail.vue'

const PARAGRAPHS_COLLECTION = 'paragraphs'
const DOCUMENTS_COLLECTION = 'documents'
const QUERY_BY = 'text'
// Mayor page size para agrupar más documentos únicos por página
const PAGE_SIZE = 50
const FAVORITES_COLLECTION = 'bible-studies-ts'

const { $i18n } = useNuxtApp()
const t = $i18n.t
const { locale } = useI18n()

const filterBy = computed(() => `locale:=${locale.value}`)
const REQUEST_TIMEOUT_MS = 15000

const query = ref('')
const debouncedQuery = useDebounce(query, 150)
const loading = ref(false)
const loadingMore = ref(false)
const errorMsg = ref<string | null>(null)

// ---- Types ----------------------------------------------------------------

interface ParagraphDoc {
  id?: string
  document_id: string
  text: string
  number: number
  locale: string
  type: string
}

interface DocMeta {
  id: string
  title: string
  date?: string
  timestamp?: number
  place?: string
  city?: string
  state?: string
  country?: string
  type?: string
  slug?: string
}

export interface DocumentDoc extends DocMeta {
  code: string
  files?: {
    youtube?: string
    video?: string
    audio?: string
    booklet?: string
    simple?: string
  }
  body?: string
  [key: string]: unknown
}

interface TypesenseHighlight {
  field?: string
  snippet?: string
  value?: string
  matched_tokens?: string[]
}

export interface TypesenseParagraphHit {
  document: ParagraphDoc
  highlights?: TypesenseHighlight[]
  highlight?: Record<string, { snippet?: string, value?: string }>
  text_match?: number
}

interface TypesenseSearchResponse {
  found: number
  hits?: TypesenseParagraphHit[]
}

// ---- State ----------------------------------------------------------------

// hits: lista plana de párrafos del buscador (sin agrupar)
const hits = ref<TypesenseParagraphHit[]>([])
const total = ref(0)
const currentPage = ref(1)
const hasMore = computed(() => hits.value.length < total.value)

// groupedHits: computed — un elemento por document_id único.
// El conteo de coincidencias por documento se omite en la lista para evitar
// confusión con el contador del find-in-document (que cuenta sobre el body
// completo). El detalle es la fuente de verdad para "cuántas coincidencias".
const groupedHits = computed(() => {
  const map = new Map<string, TypesenseParagraphHit[]>()
  for (const hit of hits.value) {
    const id = hit.document.document_id
    if (!map.has(id)) map.set(id, [])
    map.get(id)!.push(hit)
  }
  return [...map.entries()].map(([docId, docHits]) => ({
    docId,
    firstHit: docHits[0]!
  }))
})

// Cache de metadatos por document_id
const docCache = ref<Record<string, DocMeta>>({})

const { documentsApi } = useTypesenseApi()

// ---- Batch fetch de metadatos de documentos -------------------------------

async function fetchDocumentMeta(docIds: string[]) {
  const unique = docIds.filter(id => id && !(id in docCache.value))
  if (!unique.length) return
  try {
    const res = await documentsApi.multiSearch({
      multiSearchParameters: {},
      multiSearchSearchesParameter: {
        searches: [{
          collection: DOCUMENTS_COLLECTION,
          q: '*',
          queryBy: 'title',
          filterBy: `id:=[${unique.join(',')}]`,
          includeFields: 'id,title,date,timestamp,place,city,state,country,type,slug',
          perPage: unique.length,
          page: 1
        }]
      }
    })
    const docHits = (res?.results?.[0] as { hits?: Array<{ document: DocMeta }> })?.hits ?? []
    for (const hit of docHits) {
      if (hit.document.id) {
        docCache.value[hit.document.id] = hit.document
      }
    }
  } catch (err) {
    console.error('Error fetching document metadata', err)
  }
}

// ---- Búsqueda plana -------------------------------------------------------

let searchSeq = 0
let timeoutId: ReturnType<typeof setTimeout> | null = null

async function runSearch(q: string, append = false) {
  const seq = ++searchSeq
  if (append) loadingMore.value = true
  else loading.value = true
  errorMsg.value = null

  if (timeoutId) clearTimeout(timeoutId)
  timeoutId = setTimeout(() => {
    if (seq === searchSeq) {
      loading.value = false
      loadingMore.value = false
      errorMsg.value = 'La búsqueda tardó demasiado. Inténtalo de nuevo.'
    }
  }, REQUEST_TIMEOUT_MS)

  const page = append ? currentPage.value + 1 : 1

  try {
    const multi = await documentsApi.multiSearch({
      multiSearchParameters: {},
      multiSearchSearchesParameter: {
        searches: [{
          collection: PARAGRAPHS_COLLECTION,
          q: q || '*',
          queryBy: QUERY_BY,
          filterBy: filterBy.value,
          perPage: PAGE_SIZE,
          page,
          highlightFullFields: QUERY_BY,
          highlightFields: QUERY_BY,
          highlightStartTag: '<mark class="search-match">',
          highlightEndTag: '</mark>'
        }]
      }
    })

    if (seq !== searchSeq) return

    const res = (multi?.results?.[0] ?? {}) as TypesenseSearchResponse
    const newHits = res?.hits ?? []

    hits.value = append ? hits.value.concat(newHits) : newHits
    total.value = res?.found ?? hits.value.length
    currentPage.value = page

    if (!append) docCache.value = {}
    const newDocIds = [...new Set(newHits.map(h => h.document.document_id).filter(Boolean))]
    fetchDocumentMeta(newDocIds)
  } catch (err: unknown) {
    if (seq !== searchSeq) return
    console.error('Typesense error', err)
    errorMsg.value = (err as Error)?.message || 'Error al buscar.'
    if (!append) {
      hits.value = []
      total.value = 0
    }
  } finally {
    if (seq === searchSeq) {
      if (timeoutId) clearTimeout(timeoutId)
      loading.value = false
      loadingMore.value = false
    }
  }
}

function loadMore() {
  if (loadingMore.value || loading.value || !hasMore.value) return
  runSearch(query.value, true)
}

function retry() {
  runSearch(query.value, false)
}

onMounted(() => runSearch(''))
onBeforeUnmount(() => { if (timeoutId) clearTimeout(timeoutId) })

watch(debouncedQuery, (q) => {
  hits.value = []
  total.value = 0
  currentPage.value = 1
  runSearch(q, false)
})

// ---- Selección y carga del detalle ----------------------------------------

const selectedDocId = ref<string | null>(null)
const selectedDocument = ref<DocumentDoc | null>(null)
const documentLoading = ref(false)
const selectedParagraphs = ref<TypesenseParagraphHit[]>([])
const paragraphsLoading = ref(false)

async function fetchFullDocument(docId: string) {
  documentLoading.value = true
  selectedDocument.value = null
  try {
    const res = await documentsApi.multiSearch({
      multiSearchParameters: {},
      multiSearchSearchesParameter: {
        searches: [{
          collection: DOCUMENTS_COLLECTION,
          q: '*',
          queryBy: 'title',
          filterBy: `id:=${docId}`,
          perPage: 1,
          page: 1
        }]
      }
    })
    const docHits = (res?.results?.[0] as { hits?: Array<{ document: DocumentDoc }> })?.hits ?? []
    selectedDocument.value = docHits[0]?.document ?? null
  } catch (err) {
    console.error('Error fetching document', err)
    selectedDocument.value = null
  } finally {
    documentLoading.value = false
  }
}

async function fetchDocumentParagraphs(docId: string, q: string) {
  paragraphsLoading.value = true
  selectedParagraphs.value = []
  try {
    const res = await documentsApi.multiSearch({
      multiSearchParameters: {},
      multiSearchSearchesParameter: {
        searches: [{
          collection: PARAGRAPHS_COLLECTION,
          q: q || '*',
          queryBy: QUERY_BY,
          filterBy: `document_id:=${docId} && ${filterBy.value}`,
          perPage: 250,
          page: 1,
          sortBy: 'number:asc',
          highlightFullFields: QUERY_BY,
          highlightFields: QUERY_BY,
          highlightStartTag: '<mark class="search-match">',
          highlightEndTag: '</mark>'
        }]
      }
    })
    selectedParagraphs.value = (res?.results?.[0] as { hits?: TypesenseParagraphHit[] })?.hits ?? []
  } catch (err) {
    console.error('Error fetching paragraphs', err)
    selectedParagraphs.value = []
  } finally {
    paragraphsLoading.value = false
  }
}

async function selectGroup(docId: string) {
  selectedDocId.value = docId
  fetchFullDocument(docId)
  if (query.value.trim()) {
    fetchDocumentParagraphs(docId, query.value)
  } else {
    selectedParagraphs.value = []
    paragraphsLoading.value = false
  }
}

const isPanelOpen = computed({
  get() { return !!selectedDocId.value },
  set(v: boolean) {
    if (!v) {
      selectedDocId.value = null
      selectedDocument.value = null
      selectedParagraphs.value = []
    }
  }
})

watch(groupedHits, () => {
  if (!selectedDocId.value) return
  const still = groupedHits.value.find(g => g.docId === selectedDocId.value)
  if (!still) {
    selectedDocId.value = null
    selectedDocument.value = null
    selectedParagraphs.value = []
  }
})

const breakpoints = useBreakpoints(breakpointsTailwind)
const isMobile = breakpoints.smaller('lg')

useDetailHistory(isPanelOpen, isMobile)

// ---- Helpers de presentación ----------------------------------------------

function highlightedFor(hit: TypesenseParagraphHit, field: string): string | null {
  const fromArr = hit.highlights?.find(h => h.field === field)
  if (fromArr?.snippet) return fromArr.snippet
  if (fromArr?.value) return fromArr.value
  const fromObj = hit.highlight?.[field]
  if (fromObj?.snippet) return fromObj.snippet
  if (fromObj?.value) return fromObj.value
  return null
}

function metaDate(meta: DocMeta | undefined): string {
  if (!meta) return ''
  const ts = meta.timestamp || (meta.date ? Math.floor(new Date(meta.date).getTime() / 1000) : null)
  if (!ts) return meta.date || ''
  return formatDate(ts)
}

function metaLocation(meta: DocMeta | undefined): string {
  if (!meta) return ''
  return formatLocation({
    id: meta.id,
    date: meta.timestamp ?? 0,
    slug: meta.slug ?? '',
    type: meta.type ?? '',
    place: meta.place ?? '',
    city: meta.city ?? '',
    state: meta.state ?? '',
    country: meta.country ?? '',
    thumbnail: ''
  })
}
</script>

<template>
  <UDashboardPanel
    id="estudios-ts-list"
    :default-size="32"
    :min-size="24"
    :max-size="45"
    resizable
  >
    <UDashboardNavbar :title="t('nav.bible_studies_ts')">
      <template #leading>
        <UDashboardSidebarCollapse />
      </template>
      <template #trailing>
        <UBadge :label="groupedHits.length" variant="subtle" />
      </template>
    </UDashboardNavbar>

    <div class="px-4 sm:px-6 py-3 border-b border-default">
      <UInput
        v-model="query"
        icon="i-lucide-search"
        :placeholder="t('search.placeholder')"
        :loading="loading"
        size="md"
        class="w-full"
      />
      <p class="mt-1.5 flex items-center gap-1 text-[11px] text-dimmed">
        <UIcon name="i-lucide-lightbulb" class="size-3" />
        <span v-html="t('search.tip')" />
      </p>
    </div>

    <UAlert
      v-if="errorMsg"
      :title="errorMsg"
      color="error"
      variant="subtle"
      icon="i-lucide-triangle-alert"
      class="mx-4 my-2"
      :actions="[{ label: 'Reintentar', color: 'neutral', variant: 'outline', onClick: retry }]"
    />

    <div class="overflow-y-auto divide-y divide-default flex-1">
      <div
        v-if="loading && !groupedHits.length"
        class="flex items-center justify-center gap-2 py-16 text-sm text-muted"
      >
        <UIcon name="i-lucide-loader-circle" class="size-4 animate-spin" />
        Buscando...
      </div>

      <div
        v-else-if="!groupedHits.length"
        class="flex flex-col items-center justify-center gap-2 py-16 text-dimmed text-sm"
      >
        <UIcon name="i-lucide-inbox" class="size-10" />
        <p>{{ query ? `Sin coincidencias para "${query}"` : 'Sin resultados' }}</p>
      </div>

      <div
        v-for="group in groupedHits"
        :key="group.docId"
        class="bg-white p-4 sm:px-6 text-sm cursor-pointer border-l-2 transition-colors"
        :class="[
          selectedDocId === group.docId
            ? 'border-primary bg-primary/10'
            : 'border-transparent hover:border-primary hover:bg-primary/5'
        ]"
        @click="selectGroup(group.docId)"
      >
        <!-- Título -->
        <div class="mb-1">
          <p class="text-sm font-semibold line-clamp-2 text-highlighted">
            {{ docCache[group.docId]?.title || group.docId }}
          </p>
        </div>

        <!-- Fecha y lugar -->
        <p class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2 text-xs mb-2 text-muted">
          <span
            v-if="metaDate(docCache[group.docId])"
            class="flex items-center gap-1"
          >
            <UIcon name="ph:calendar" class="size-4 text-green-600" />
            {{ metaDate(docCache[group.docId]) }}
          </span>
          <span
            v-if="metaLocation(docCache[group.docId])"
            class="flex items-center gap-1 truncate"
          >
            <UIcon name="ph:map-pin" class="size-4 text-green-600 shrink-0" />
            <span class="truncate">{{ metaLocation(docCache[group.docId]) }}</span>
          </span>
        </p>

        <!-- Primer párrafo coincidente con highlight -->
        <div
          class="snippet-html text-sm text-dimmed line-clamp-3"
          v-html="highlightedFor(group.firstHit, 'text') || group.firstHit.document.text"
        />
      </div>

      <div
        v-if="hasMore && !loading"
        class="p-4 flex justify-center"
      >
        <UButton
          variant="outline"
          color="neutral"
          size="sm"
          :loading="loadingMore"
          @click="loadMore"
        >
          Cargar más
        </UButton>
      </div>

      <div
        v-else-if="groupedHits.length && !hasMore && !loading"
        class="py-3 text-center text-xs text-dimmed"
      >
        No hay más resultados
      </div>
    </div>
  </UDashboardPanel>

  <!-- Panel de detalle (escritorio) -->
  <EstudiosTypensenseDetail
    v-if="selectedDocId && !isMobile"
    :document="selectedDocument"
    :document-loading="documentLoading"
    :paragraphs="selectedParagraphs"
    :paragraphs-loading="paragraphsLoading"
    :collection="FAVORITES_COLLECTION"
    :query="debouncedQuery"
    @close="isPanelOpen = false"
  />
  <div v-else-if="!isMobile" class="hidden lg:flex flex-1 items-center justify-center">
    <div class="flex flex-col items-center gap-2 text-dimmed">
      <UIcon name="i-lucide-search" class="size-16" />
      <p class="text-sm">Selecciona una actividad para ver el detalle</p>
    </div>
  </div>

  <!-- Panel de detalle (móvil) -->
  <ClientOnly>
    <USlideover v-if="isMobile" v-model:open="isPanelOpen">
      <template #content>
        <EstudiosTypensenseDetail
          v-if="selectedDocId"
          :document="selectedDocument"
          :document-loading="documentLoading"
          :paragraphs="selectedParagraphs"
          :paragraphs-loading="paragraphsLoading"
          :collection="FAVORITES_COLLECTION"
          :query="debouncedQuery"
          @close="isPanelOpen = false"
        />
      </template>
    </USlideover>
  </ClientOnly>
</template>

<style scoped>
.snippet-html :deep(p) {
  display: inline;
  margin: 0;
}
.snippet-html :deep(br) {
  display: none;
}
</style>
