<template>
  <FilterBar 
    v-if="fieldsWithId.length > 0"
    :fields="fieldsWithId"
    :model-value="filters"
    :show-sort="true"
    :sort-by="sortBy"
    :sort-order="sortOrder"
    :page-meta="pageMeta"
    @update:model-value="handleUpdateFilters"
    @filter-change="handleFilterChange"
    @update:sort-by="handleUpdateSortBy"
    @update:sort-order="handleUpdateSortOrder"
    @sort-change="handleSortChange"
  />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import FilterBar from '@/core/components/FilterBar.vue'

interface Props {
  fields: any[]
  filters: Record<string, any>
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
  pageMeta?: any
}

interface Emits {
  (e: 'update:filters', value: Record<string, any>): void
  (e: 'filter-change'): void
  (e: 'update:sortBy', value: string): void
  (e: 'update:sortOrder', value: 'asc' | 'desc'): void
  (e: 'sortChange', sortBy: string, sortOrder: 'asc' | 'desc'): void
}

const props = withDefaults(defineProps<Props>(), {
  sortBy: 'modified',
  sortOrder: 'desc',
  pageMeta: undefined
})
const emit = defineEmits<Emits>()

// Ensure ID field is first (unless hide_id_in_list)
const fieldsWithId = computed(() => {
  const existingFields = props.fields || []
  const hideId = props.pageMeta?.hide_id_in_list === 1 || props.pageMeta?.hide_id_in_list === true
  
  if (hideId) {
    return existingFields.filter(f => f.fieldname !== 'name')
  }
  
  // Check if name field exists
  const hasNameField = existingFields.some(f => f.fieldname === 'name')
  
  if (hasNameField) {
    // Move name field to first position
    const nameField = existingFields.find(f => f.fieldname === 'name')
    const otherFields = existingFields.filter(f => f.fieldname !== 'name')
    return [nameField, ...otherFields]
  } else {
    // Add ID field to first position
    const idField = {
      fieldname: 'name',
      label: 'ID',
      fieldtype: 'Data',
      in_standard_filter: 1
    }
    return [idField, ...existingFields]
  }
})

function handleUpdateFilters(value: Record<string, any>) {
  emit('update:filters', value)
}

function handleFilterChange() {
  emit('filter-change')
}

function handleUpdateSortBy(value: string) {
  emit('update:sortBy', value)
}

function handleUpdateSortOrder(value: 'asc' | 'desc') {
  emit('update:sortOrder', value)
}

function handleSortChange(sortBy: string, sortOrder: 'asc' | 'desc') {
  emit('sortChange', sortBy, sortOrder)
}
</script>

<style scoped>
/* Filter bar styles handled by FilterBar component */
</style>
