<template>
  <div class="sort-selector">
    <div class="sort-controls">
      <!-- Sort order toggle button -->
      <button 
        class="sort-order-btn"
        :title="sortOrder === 'desc' ? t('Descending') : t('Ascending')"
        @click="toggleSortOrder"
      >
        <Icon 
          :icon="sortOrder === 'desc' ? 'mdi:sort-descending' : 'mdi:sort-ascending'" 
          :width="16" 
          :height="16"
        />
      </button>
      
      <!-- Sort field selector -->
      <n-dropdown 
        :options="sortOptions" 
        @select="handleFieldSelect"
        trigger="click"
        placement="bottom-end"
      >
        <button class="sort-field-btn">
          <span class="sort-field-text">{{ currentSortLabel }}</span>
          <Icon icon="mdi:chevron-down" :width="16" :height="16" />
        </button>
      </n-dropdown>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'
import { NDropdown } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'

interface SortOption {
  fieldname: string
  label: string
}

interface Props {
  sortBy: string
  sortOrder: 'asc' | 'desc'
  options?: SortOption[]
  pageMeta?: any
}

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

const emit = defineEmits<{
  (e: 'update:sortBy', value: string): void
  (e: 'update:sortOrder', value: 'asc' | 'desc'): void
  (e: 'change', sortBy: string, sortOrder: 'asc' | 'desc'): void
}>()

// Compute sort options based on pagetype metadata (aligned with old version)
const sortOptions = computed(() => {
  if (props.options && props.options.length > 0) {
    return props.options.map(opt => ({
      label: t(opt.label),
      key: opt.fieldname
    }))
  }
  
  // Default options aligned with old version sort_selector.js line 123-138
  const defaultOptions: SortOption[] = [
    { fieldname: 'modified', label: 'Modified' },
    { fieldname: 'name', label: 'ID' },
    { fieldname: 'creation', label: 'Created' },
    { fieldname: 'idx', label: 'Most Used' }
  ]
  
  // Add title_field if available
  if (props.pageMeta?.title_field && props.pageMeta.title_field !== 'name') {
    const titleFieldLabel = props.pageMeta.title_field.charAt(0).toUpperCase() + props.pageMeta.title_field.slice(1)
    defaultOptions.splice(1, 0, { fieldname: props.pageMeta.title_field, label: titleFieldLabel })
  }
  
  // Add sort_field if configured in PageType
  if (props.pageMeta?.sort_field && props.pageMeta.sort_field !== 'modified') {
    const sortFieldLabel = props.pageMeta.sort_field.charAt(0).toUpperCase() + props.pageMeta.sort_field.slice(1)
    defaultOptions.splice(1, 0, { fieldname: props.pageMeta.sort_field, label: sortFieldLabel })
  }
  
  // Add fields that are in_list_view, mandatory, or bold (aligned with old version line 141-149)
  if (props.pageMeta?.fields) {
    props.pageMeta.fields.forEach((field: any) => {
      if ((field.in_list_view || field.mandatory || field.bold || field.reqd) && 
          isValueField(field.fieldtype) &&
          !defaultOptions.find(opt => opt.fieldname === field.fieldname)) {
        defaultOptions.push({ 
          fieldname: field.fieldname, 
          label: field.label || field.fieldname 
        })
      }
    })
  }
  
  // De-duplicate
  const uniqueOptions = Array.from(
    new Map(defaultOptions.map(opt => [opt.fieldname, opt])).values()
  )
  
  return uniqueOptions.map(opt => ({
    label: t(opt.label),
    key: opt.fieldname
  }))
})

// Check if field is value field (aligned with jingrow.model.is_value_type)
function isValueField(fieldtype: string): boolean {
  const valueTypes = [
    'Data', 'Text', 'Small Text', 'Long Text', 'Link', 'Dynamic Link',
    'Date', 'Datetime', 'Time', 'Check', 'Select', 'Int', 'Float', 'Currency',
    'Percent', 'Duration', 'Rating', 'Code', 'Text Editor', 'HTML Editor',
    'Markdown Editor', 'Barcode', 'Geolocation', 'Color', 'Icon', 'Attach Image'
  ]
  return valueTypes.includes(fieldtype)
}

// Get current sort field label
const currentSortLabel = computed(() => {
  const option = sortOptions.value.find(opt => opt.key === props.sortBy)
  return option?.label || t('Modified')
})

// Toggle sort order
function toggleSortOrder() {
  const newOrder = props.sortOrder === 'desc' ? 'asc' : 'desc'
  emit('update:sortOrder', newOrder)
  emit('change', props.sortBy, newOrder)
}

// Handle field selection
function handleFieldSelect(key: string) {
  emit('update:sortBy', key)
  emit('change', key, props.sortOrder)
}
</script>

<style scoped>
.sort-selector {
  display: flex;
  align-items: center;
  gap: 0;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 0;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  overflow: hidden;
  background: white;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.sort-controls:hover {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.sort-order-btn,
.sort-field-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 6px 12px;
  height: 32px;
  border: none;
  background: transparent;
  color: #374151;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  white-space: nowrap;
}

.sort-order-btn {
  padding: 6px 8px;
  border-right: 1px solid #e5e7eb;
}

.sort-order-btn:hover {
  background: #f3f4f6;
  color: #3b82f6;
}

.sort-field-btn {
  min-width: 100px;
}

.sort-field-btn:hover {
  background: #f3f4f6;
  color: #3b82f6;
}

.sort-field-text {
  flex: 1;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
