<template>
  <div class="fc-dlf">
    <v-menu :close-on-content-click="false" v-model="open">
      <template #activator="{ props }">
        <v-btn v-bind="props" variant="outlined" prepend-icon="mdi-filter-variant">
          Filter
          <v-chip v-if="activeCount" size="x-small" color="accent" class="ms-2">
            {{ activeCount }}
          </v-chip>
        </v-btn>
      </template>
      <v-card min-width="340" class="pa-3">
        <v-select
          v-model="local.status"
          :items="STATUS_OPTIONS"
          label="Status"
          density="compact" variant="outlined" hide-details clearable
          class="mb-2"
        />
        <v-autocomplete
          v-model="local.artist_id"
          :items="artistItems"
          :loading="artistLoading"
          label="Artist"
          item-title="name" item-value="id"
          density="compact" variant="outlined" hide-details clearable
          no-filter
          class="mb-2"
          @update:search="onArtistSearch"
          @update:model-value="onArtistPick"
        />
        <v-text-field
          v-model="local.from_date"
          label="From"
          density="compact" variant="outlined" hide-details clearable
          type="date"
          class="mb-2"
        />
        <v-text-field
          v-model="local.to_date"
          label="To"
          density="compact" variant="outlined" hide-details clearable
          type="date"
          class="mb-3"
        />
        <div class="d-flex">
          <v-btn variant="text" size="small" @click="reset">Reset</v-btn>
          <v-spacer />
          <v-btn color="accent" size="small" @click="apply">Apply</v-btn>
        </div>
      </v-card>
    </v-menu>

    <div v-if="activeCount" class="fc-dlf__pills mt-2">
      <v-chip
        v-for="p in activePills" :key="p.key"
        size="small" closable variant="tonal"
        @click:close="clearOne(p.key)"
      >
        {{ p.label }}
      </v-chip>
      <v-btn variant="text" size="x-small" @click="reset">Clear all</v-btn>
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue'

import { useSourcesStore } from '../../stores/sources.js'
import { DOWNLOAD_STATUSES, downloadStatusLabel } from '../../utils/downloadStatus.js'

const props = defineProps({
  modelValue: { type: Object, required: true },
})
const emit = defineEmits(['update:modelValue'])

const sourcesStore = useSourcesStore()

const STATUS_OPTIONS = DOWNLOAD_STATUSES.map((s) => ({ title: s.label, value: s.value }))

const open = ref(false)
const local = reactive({
  status:      props.modelValue.status ?? null,
  artist_id:   props.modelValue.artist_id ?? null,
  artist_name: props.modelValue.artist_name ?? null,
  from_date:   props.modelValue.from_date ?? null,
  to_date:     props.modelValue.to_date ?? null,
})

watch(() => props.modelValue, (v) => Object.assign(local, v), { deep: true })

// Artist autocomplete for the filter (replaces the old numeric Source-ID
// field — operator-flagged 2026-05-28). Keeps the currently-selected
// artist in the items list so the chip label resolves even before a
// search runs.
const artistItems = ref([])
const artistLoading = ref(false)
let artistDebounce = null
function onArtistSearch(q) {
  if (artistDebounce) clearTimeout(artistDebounce)
  if (!q || !q.trim()) { return }
  artistDebounce = setTimeout(async () => {
    artistLoading.value = true
    try {
      artistItems.value = await sourcesStore.autocompleteArtist(q.trim(), 20)
    } finally {
      artistLoading.value = false
    }
  }, 250)
}
function onArtistPick(id) {
  const hit = artistItems.value.find((a) => a.id === id)
  local.artist_name = hit ? hit.name : null
}

const activePills = computed(() => {
  const out = []
  if (local.status)    out.push({ key: 'status',    label: `Status: ${downloadStatusLabel(local.status)}` })
  if (local.artist_id) out.push({ key: 'artist_id', label: `Artist: ${local.artist_name || `#${local.artist_id}`}` })
  if (local.from_date) out.push({ key: 'from_date', label: `From ${local.from_date}` })
  if (local.to_date)   out.push({ key: 'to_date',   label: `To ${local.to_date}` })
  return out
})
const activeCount = computed(() => activePills.value.length)

function apply() {
  emit('update:modelValue', { ...local })
  open.value = false
}
function reset() {
  local.status = null
  local.artist_id = null
  local.artist_name = null
  local.from_date = null
  local.to_date = null
  emit('update:modelValue', { ...local })
}
function clearOne(key) {
  if (key === 'artist_id') {
    local.artist_id = null
    local.artist_name = null
  } else {
    local[key] = null
  }
  emit('update:modelValue', { ...local })
}
</script>

<style scoped>
.fc-dlf__pills {
  display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
}
</style>
