<script setup lang="ts">
import { computed, ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { breakpointsTailwind } from '@vueuse/core'
import PublicationDetail from '~/components/PublicationDetail.vue'
import FiltersContainer from '~/components/searchPanel/FiltersContainer.vue'
import { useSettingsStore } from '~/stores/settings'

interface Props {
  paragraphsCollection: string
  mainCollection: string
  groupByField: string
  favoritesCollection: string
  panelId: string
  navTitleKey: string
  accentColor: 'green' | 'blue'
  emptyDetailText: string
  showDraft?: boolean
  author?: string
  showBibleStudyFilter?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showDraft: false,
  author: '',
  showBibleStudyFilter: false
})

const QUERY_BY = 'text'

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

const settings = useSettingsStore()
const { unlocked } = useDevMode()
const toast = useToast()
const typesenseClient = useTypesenseClient()

// ── Restaurar estado desde URL antes de crear los refs ─────────────────────
const { query: q0, page: p0, scroll: s0, selectedId: sid0 } = useSearchUrlState()

// ---- Filtro bible_study multi-chip (solo para Estudios) --------------------

interface BibleStudyChip {
  id: number
  title: string
}

const bibleStudyInput = ref<number | null>(null)
const activeBibleStudies = ref<BibleStudyChip[]>([])
const isValidating = ref(false)

const {
  query, debouncedQuery, loading, loadingMore, errorMsg,
  exactSearch, sortMode,
  groupedHits, visibleGroupCount, visibleGroups, hasMoreVisible, hasMore,
  browseItems, hasMoreBrowse,
  displayGroups, activePage, displayTotal, totalPages,
  runSearch, runBrowse, loadMore, goToPage, retry
} = useGroupedTypesenseSearch({
  paragraphsCollection: props.paragraphsCollection,
  mainCollection: props.mainCollection,
  groupByField: props.groupByField,
  queryBy: QUERY_BY,
  filterBy: () => {
    let base = `locale:=${locale.value}`
    if (activeBibleStudies.value.length > 0) {
      const ids = activeBibleStudies.value.map(bs => bs.id).join(',')
      base += ` && $${props.mainCollection}(bible_study:=[${ids}])`
    }
    return base
  },
  browseFilterBy: () => {
    let base = `locale:=${locale.value}`
    if (activeBibleStudies.value.length > 0) {
      const ids = activeBibleStudies.value.map(bs => bs.id).join(',')
      base += ` && bible_study:=[${ids}]`
    }
    return base
  },
  isUnlocked: () => unlocked.value,
  pageSize: () => settings.pageSize,
  paginationType: () => settings.paginationType,
  initialQuery: q0,
  initialPage: p0
})

function refetchResults() {
  if (!debouncedQuery.value.trim()) {
    browseItems.value = []
    runBrowse(1, false)
  } else {
    groupedHits.value = []
    runSearch(query.value, 1, false)
  }
}

async function applyBibleStudyFilter() {
  const val = bibleStudyInput.value
  if (val === null || val <= 0) return
  if (activeBibleStudies.value.some(bs => bs.id === val)) {
    toast.add({ title: 'Estudio ya agregado', description: `El estudio #${val} ya está en el filtro`, color: 'info' })
    bibleStudyInput.value = null
    return
  }

  isValidating.value = true
  try {
    const res = await typesenseClient.multiSearch.perform({
      searches: [{
        collection: props.mainCollection,
        q: '*',
        query_by: 'title',
        filter_by: `bible_study:=${val}`,
        per_page: 1,
        include_fields: 'bible_study,title',
        use_cache: true,
        cache_ttl: 3600
      }]
    })

    const hit = (res?.results?.[0] as { hits?: Array<{ document: { title?: string } }> })?.hits?.[0]
    if (hit) {
      activeBibleStudies.value = [...activeBibleStudies.value, { id: val, title: hit.document.title || '' }]
      bibleStudyInput.value = null
      refetchResults()
    } else {
      toast.add({ title: 'Estudio no encontrado', description: `No existe el estudio #${val}`, color: 'warning' })
    }
  } catch (err) {
    console.error('Error validando bible_study', err)
  } finally {
    isValidating.value = false
  }
}

function removeBibleStudyFilter(id: number) {
  activeBibleStudies.value = activeBibleStudies.value.filter(bs => bs.id !== id)
  refetchResults()
}

function clearAllBibleStudyFilters() {
  activeBibleStudies.value = []
  refetchResults()
}

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

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

// ---- Colors ----------------------------------------------------------------

const colors = computed(() => {
  if (props.accentColor === 'green') {
    return {
      selectedItem: 'border-carpagreen bg-carpagreen/10',
      hoverItem: 'border-gray-200 hover:border-carpagreen hover:bg-carpagreen/5',
      icon: 'text-carpagreen',
    }
  }
  return {
    selectedItem: 'border-carpablue bg-carpablue/10',
    hoverItem: 'border-gray-200 hover:border-carpablue hover:bg-carpablue/5',
    icon: 'text-carpablue',
  }
})

// ---- Scroll infinito y detalle ---------------------------------------------

const listContainer = ref<HTMLElement | null>(null)

function onListScroll() {
  if (settings.paginationType !== 'infinite_scroll') return
  const el = listContainer.value
  if (!el) return
  if (el.scrollHeight - el.scrollTop - el.clientHeight < 200) {
    if (!debouncedQuery.value.trim()) {
      if (hasMoreBrowse.value && !loadingMore.value && !loading.value) runBrowse(1, true)
    } else {
      if (hasMoreVisible.value) visibleGroupCount.value += 10
      else if (hasMore.value && !loadingMore.value && !loading.value) loadMore()
    }
  }
}

// ---- 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<TypesenseGroupedParagraphHit[]>([])
const paragraphsLoading = ref(false)
const selectedHit = ref<TypesenseGroupedParagraphHit | null>(null)
const selectedMatchingHits = ref<TypesenseGroupedParagraphHit[]>([])

let detailSeq = 0
let detailController: AbortController | null = null

onBeforeUnmount(() => { detailController?.abort() })

const { fetchDocumentDetail } = useDocumentDetailFetch()

async function fetchDocumentWithParagraphs(docId: string) {
  const seq = ++detailSeq
  detailController?.abort()
  const controller = new AbortController()
  detailController = controller
  documentLoading.value = true
  paragraphsLoading.value = true
  selectedDocument.value = null
  selectedParagraphs.value = []
  try {
    const detail = await fetchDocumentDetail(typesenseClient, props.mainCollection, props.paragraphsCollection, docId, controller.signal)
    if (seq !== detailSeq) return
    if (detail) {
      const rawParagraphs = detail.paragraphs as unknown as ParagraphDoc[]
      selectedDocument.value = detail.document as unknown as DocumentDoc
      selectedParagraphs.value = [...rawParagraphs]
        .sort((a, b) => (a.number ?? 0) - (b.number ?? 0))
        .map(p => ({ document: p }))
    }
  } catch (err) {
    if (seq !== detailSeq) return
    if ((err as { name?: string })?.name === 'AbortError') return
    console.error('Error fetching document with paragraphs', err)
    selectedDocument.value = null
    selectedParagraphs.value = []
  } finally {
    if (seq === detailSeq) {
      documentLoading.value = false
      paragraphsLoading.value = false
    }
  }
}

async function selectGroup(group: DisplayGroup) {
  selectedDocId.value = group.docId
  selectedHit.value = group.firstHit
  selectedMatchingHits.value = groupedHits.value.find(g => g.docId === group.docId)?.allHits ?? []
  fetchDocumentWithParagraphs(group.docId)
}

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

watch(groupedHits, () => {
  if (!selectedDocId.value || !debouncedQuery.value.trim()) return
  if (!groupedHits.value.find(g => g.docId === selectedDocId.value)) {
    selectedDocId.value = null
    selectedDocument.value = null
    selectedParagraphs.value = []
    selectedHit.value = null
    selectedMatchingHits.value = []
  }
})

const selectedId = computed(() => selectedDocId.value)

useSearchUrlSync({ query, page: activePage, selectedId, scrollEl: listContainer })

onMounted(async () => {
  if (q0.trim()) await runSearch(q0, p0, false)
  else await runBrowse(p0, false)

  restoreScrollPosition(listContainer.value, s0)

  if (sid0) {
    const group = displayGroups.value.find(g => g.docId === sid0)
    if (group) selectGroup(group)
    else {
      selectedDocId.value = sid0
      fetchDocumentWithParagraphs(sid0)
    }
  }
})

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

useDetailHistory(isPanelOpen, isMobile)

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

function highlightedFor(hit: TypesenseGroupedParagraphHit, 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: CachedDocMeta | 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: CachedDocMeta | 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="panelId"
    :default-size="32"
    :min-size="24"
    :max-size="45"
    resizable
  >
    <UDashboardNavbar :title="t(navTitleKey)">
      <template #leading>
        <UDashboardSidebarCollapse :ui="{
          base: 'collapse-sidebar-icon'
        }" />
      </template>
      <template #trailing>
        <UBadge :label="displayTotal" variant="subtle" :ui="{
          base: 'total-results'
        }" />
      </template>
    </UDashboardNavbar>

    <div
      v-if="author"
      class="px-4 sm:px-6 py-2 border-b border-default flex items-center gap-1.5 text-xs text-muted"
    >
      <UIcon name="ph:user-circle" :class="['size-3.5 shrink-0', colors.icon]" />
      <span class="italic">{{ author }}</span>
    </div>

    <!-- ─── BUSCADOR ─────────────────────────────────── -->
    <div class="px-4 sm:px-6 py-3 border-b border-default flex items-center gap-2" id="inputField">
      <UInput
        v-model="query"
        icon="i-lucide-search"
        :placeholder="t('search.placeholder')"
        :loading="loading"
        size="md"
        class="flex-1 min-w-0"
      />
      <div
        class="flex rounded-full p-0.5 shrink-0 transition-colors duration-200"
        :class="exactSearch ? 'bg-primary' : 'bg-gray-200 dark:bg-gray-700'"
      >
        <button
          class="px-2.5 py-0.5 rounded-full text-xs transition-all duration-200 whitespace-nowrap"
          :class="!exactSearch ? 'bg-white dark:bg-gray-900 text-gray-900 dark:text-white font-semibold shadow-sm' : 'text-white/40 font-normal'"
          @click.stop="exactSearch = false"
        >{{ t('search.word') }}</button>
        <button
          class="px-2.5 py-0.5 rounded-full text-xs transition-all duration-200 whitespace-nowrap"
          :class="exactSearch ? 'bg-white text-primary font-semibold shadow-sm' : 'text-gray-400 dark:text-gray-400 font-normal'"
          @click.stop="exactSearch = true"
        >{{ t('search.phrase') }}</button>
      </div>
    </div>

    <!-- ─── CHIPS ACTIVOS (solo desktop: fuera del FiltersContainer) ─── -->
    <div v-if="showBibleStudyFilter && activeBibleStudies.length > 0 && !isMobile" class="px-4 sm:px-6 py-2 border-b border-default">
      <div class="flex flex-wrap items-center gap-1.5">
        <UBadge
          v-for="bs in activeBibleStudies"
          :key="bs.id"
          size="sm"
          variant="subtle"
          color="primary"
          class="max-w-full"
        >
          <span class="truncate">{{ $t('search.bible_study_chip', { number: bs.id }) }}</span>
          <UButton
            icon="i-lucide-x"
            size="2xs"
            color="neutral"
            variant="ghost"
            class="ml-1 shrink-0"
            @click="removeBibleStudyFilter(bs.id)"
          />
        </UBadge>
        <UButton
          size="2xs"
          color="neutral"
          variant="ghost"
          class="text-xs"
          @click="clearAllBibleStudyFilters"
        >
          {{ $t('search.bible_study_clear') }}
        </UButton>
      </div>
    </div>

    <!-- ─── SORT ────────────────────────────────────── -->
    <div v-if="query.trim()" class="px-4 sm:px-6 py-3 flex items-center gap-2">
      <p class="text-sm">Busqueda: </p>
      <USelect
        v-model="sortMode"
        :items="[
          { label: t('search.sort.relevance'), value: 'relevance' },
          { label: t('search.sort.date'), value: 'date' }
        ]"
        size="sm"
        class="shrink-0 min-w-[130px]"
      />
    </div>

    <!-- ─── FILTROS: AGREGAR NUEVOS (acordeón desktop / slideover mobile) ─── -->
    <template v-if="showBibleStudyFilter">
      <FiltersContainer
        :active-count="activeBibleStudies.length"
        title="search.filters"
      >
        <template #chips>
          <div class="flex flex-wrap items-center gap-1.5">
            <UBadge
              v-for="bs in activeBibleStudies"
              :key="bs.id"
              size="sm"
              variant="subtle"
              color="primary"
              class="max-w-full"
            >
              <span class="truncate">{{ $t('search.bible_study_chip', { number: bs.id }) }}</span>
              <UButton
                icon="i-lucide-x"
                size="2xs"
                color="neutral"
                variant="ghost"
                class="ml-1 shrink-0"
                @click="removeBibleStudyFilter(bs.id)"
              />
            </UBadge>
            <div v-if="activeBibleStudies.length > 0">
              <UButton
                size="sm"
                color="neutral"
                variant="ghost"
                class="text-xs"
                @click="clearAllBibleStudyFilters">
                {{ $t('search.bible_study_clear') }}
              </UButton>
            </div>
          </div>
        </template>
        <template #content>
          <div class="flex items-center gap-2">
            <UInput
              v-model="bibleStudyInput"
              type="number"
              min="1"
              :placeholder="$t('search.bible_study_placeholder')"
              size="sm"
              class="w-36"
              @keyup.enter="applyBibleStudyFilter"
            />
            <UButton
              size="sm"
              color="neutral"
              variant="outline"
              :loading="isValidating"
              :disabled="bibleStudyInput === null || bibleStudyInput <= 0"
              @click="applyBibleStudyFilter"
            >
              + {{ $t('search.filter') }}
            </UButton>
          </div>
        </template>
      </FiltersContainer>
    </template>

    <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 ref="listContainer" class="overflow-y-auto divide-y divide-default flex-1" @scroll="onListScroll">
      <div
        v-if="loading && !displayGroups.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="!displayGroups.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 displayGroups"
        :key="group.docId"
        class="p-4 sm:px-6 text-sm cursor-pointer border-b-2 transition-colors"
        :class="selectedDocId === group.docId ? colors.selectedItem : colors.hoverItem"
        @click="selectGroup(group)"
      >
        <div class="mb-1">
          <p class="text-sm font-semibold line-clamp-2 text-highlighted">
            <UTooltip
              v-if="showDraft && group.meta?.draft"
              :text="$t('search.draft')"
              color="error"
            >
              <UIcon name="ph-file-dashed" class="bg-carpared" />
            </UTooltip>
            {{ group.meta?.title || group.docId }}
          </p>
        </div>

        <p class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2 text-xs mb-2 text-muted justify-between">
          <span v-if="metaDate(group.meta)" class="flex items-center gap-1">
            <UIcon name="ph:calendar" :class="['size-4', colors.icon]" />
            {{ metaDate(group.meta) }}
          </span>
          <span v-if="metaLocation(group.meta)" class="flex items-center gap-1 truncate">
            <UIcon name="ph:map-pin" :class="['size-4 shrink-0', colors.icon]" />
            <span class="truncate">{{ metaLocation(group.meta) }}</span>
          </span>
        </p>

        <div
          v-if="group.firstHit"
          class="snippet-html text-sm text-dimmed"
          v-html="highlightedFor(group.firstHit, 'text') || group.firstHit.document.text"
        />
      </div>

      <div
        v-if="settings.paginationType === 'infinite_scroll' && loadingMore"
        class="flex items-center justify-center gap-2 py-4 text-sm text-muted"
      >
        <UIcon name="i-lucide-loader-circle" class="size-4 animate-spin" />
        Cargando más...
      </div>

      <div
        v-else-if="settings.paginationType === 'infinite_scroll' && displayGroups.length && !hasMoreBrowse && !hasMoreVisible && !hasMore && !loading"
        class="py-3 text-center text-xs text-dimmed"
      >
        No hay más resultados
      </div>
    </div>

    <div
      v-if="settings.paginationType === 'numbered' && totalPages > 1 && !loading"
      class="px-4 py-3 border-t border-default flex justify-center shrink-0"
    >
      <UPagination
        :page="activePage"
        :total="displayTotal"
        :items-per-page="settings.pageSize"
        size="sm"
        @update:page="goToPage"
      />
    </div>
  </UDashboardPanel>

  <!-- Panel de detalle (escritorio) -->
  <PublicationDetail
    v-if="selectedDocId && !isMobile"
    :document="selectedDocument"
    :document-loading="documentLoading"
    :paragraphs="selectedParagraphs"
    :paragraphs-loading="paragraphsLoading"
    :collection="favoritesCollection"
    :query="debouncedQuery"
    :selected-hit="selectedHit"
    :selected-matching-hits="selectedMatchingHits"
    :accent-color="accentColor"
    :author="author"
    @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">{{ emptyDetailText }}</p>
    </div>
  </div>

  <!-- Panel de detalle (móvil) -->
  <ClientOnly>
    <USlideover v-if="isMobile" v-model:open="isPanelOpen">
      <template #content>
        <PublicationDetail
          v-if="selectedDocId"
          :document="selectedDocument"
          :document-loading="documentLoading"
          :paragraphs="selectedParagraphs"
          :paragraphs-loading="paragraphsLoading"
          :collection="favoritesCollection"
          :query="debouncedQuery"
          :selected-hit="selectedHit"
          :selected-matching-hits="selectedMatchingHits"
          :accent-color="accentColor"
          :author="author"
          @close="isPanelOpen = false"
        />
      </template>
    </USlideover>
  </ClientOnly>
</template>

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