<template>
  <n-modal
    v-model:show="visible"
    preset="dialog"
    :title="editing ? t('Edit Quick List') : t('Add Quick List')"
    :positive-text="editing ? t('Save') : t('Add')"
    :negative-text="t('Cancel')"
    @positive-click="handleSubmit"
    @negative-click="handleCancel"
    style="width: 500px;"
  >
    <div class="dialog-content">
      <div class="form-row">
        <LinkField
          v-model="formData.document_type"
          :options="'PageType'"
          :label="t('PageType')"
          :required="true"
          placeholder=""
          :enable-create="false"
          :get-query="getPageTypeQuery"
        />
        
        <div class="form-field">
          <label class="field-label">{{ t('Label') }}</label>
          <n-input
            v-model:value="formData.label"
            placeholder=""
          />
        </div>
      </div>
      
      <!-- Filter section -->
      <div v-if="formData.document_type" class="filter-section">
        <n-divider>{{ t('Add Filters') }}</n-divider>
        
        <div v-if="filters.length > 0" class="filters-list">
          <div v-for="(filter, index) in filters" :key="index" class="filter-row">
            <n-select
              v-model:value="filter.fieldname"
              :options="fieldOptions"
              size="small"
              class="filter-field"
              :disabled="pageTypeFields.length === 0"
            />
            <n-select
              v-model:value="filter.condition"
              :options="getConditionOptions(filter)"
              size="small"
              class="filter-condition"
            />
            <n-input
              v-model:value="filter.value"
              size="small"
              class="filter-value"
              placeholder=""
            />
            <n-button size="small" quaternary type="error" @click="removeFilter(index)">
              <template #icon>
                <Icon icon="mdi:close" />
              </template>
            </n-button>
          </div>
        </div>
        
        <n-button 
          size="small" 
          dashed 
          @click="addFilter" 
          class="add-filter-btn"
          :disabled="pageTypeFields.length === 0"
          :loading="isLoadingFields"
        >
          <template #icon>
            <Icon icon="mdi:plus" />
          </template>
          {{ t('Add Filter') }}
        </n-button>
        
        <n-button v-if="filters.length > 0" size="small" quaternary @click="clearFilters" style="margin-left: 8px;">
          {{ t('Clear Filters') }}
        </n-button>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { NModal, NInput, NSelect, NButton, NDivider, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { getPageTypeMeta } from '@/shared/api/common'
import LinkField from '@/shared/components/LinkField.vue'

interface FilterItem {
  fieldname: string
  condition: string
  value: string
}

const props = defineProps<{
  show: boolean
  values?: {
    document_type?: string
    label?: string
    quick_list_filter?: string
    name?: string
  }
}>()

const emit = defineEmits<{
  'update:show': [value: boolean]
  'submit': [data: any]
}>()

const message = useMessage()

const visible = computed({
  get: () => props.show,
  set: (val) => emit('update:show', val)
})

const editing = computed(() => !!props.values?.name)

const formData = reactive({
  document_type: '',
  label: '',
  quick_list_filter: '',
  name: ''
})

const filters = ref<FilterItem[]>([])
const pageTypeFields = ref<any[]>([])
const isLoadingFields = ref(false)

const fieldOptions = computed(() => {
  return pageTypeFields.value.map(field => ({
    label: field.label || field.fieldname,
    value: field.fieldname
  }))
})

function getConditionOptions(filter: FilterItem) {
  const field = pageTypeFields.value.find(f => f.fieldname === filter.fieldname)
  if (!field) return [{ label: '=', value: '=' }]
  
  const fieldtype = field.fieldtype
  
  if (['Data', 'Text', 'Small Text', 'Long Text', 'Text Editor'].includes(fieldtype)) {
    return [
      { label: '=', value: '=' },
      { label: '!=', value: '!=' },
      { label: 'like', value: 'like' },
      { label: 'not like', value: 'not like' }
    ]
  } else if (['Int', 'Float', 'Currency', 'Percent'].includes(fieldtype)) {
    return [
      { label: '=', value: '=' },
      { label: '!=', value: '!=' },
      { label: '>', value: '>' },
      { label: '<', value: '<' },
      { label: '>=', value: '>=' },
      { label: '<=', value: '<=' }
    ]
  } else if (['Link', 'Select'].includes(fieldtype)) {
    return [
      { label: '=', value: '=' },
      { label: '!=', value: '!=' }
    ]
  }
  
  return [
    { label: '=', value: '=' },
    { label: '!=', value: '!=' }
  ]
}

function getPageTypeQuery() {
  return {
    filters: {
      issingle: 0,
      istable: 0
    }
  }
}

async function loadPageTypeFields(pagetype: string) {
  if (!pagetype) {
    pageTypeFields.value = []
    return
  }
  
  isLoadingFields.value = true
  try {
    const result = await getPageTypeMeta(pagetype)
    
    if (result.success && result.data?.fields) {
      pageTypeFields.value = result.data.fields
    } else {
      console.error('Failed to load PageType meta:', result.message)
      pageTypeFields.value = []
    }
  } catch (error) {
    console.error('Failed to load PageType fields:', error)
    pageTypeFields.value = []
  } finally {
    isLoadingFields.value = false
  }
}

function addFilter() {
  if (pageTypeFields.value.length === 0) return
  
  filters.value.push({
    fieldname: pageTypeFields.value[0]?.fieldname || 'name',
    condition: '=',
    value: ''
  })
}

function removeFilter(index: number) {
  filters.value.splice(index, 1)
}

function clearFilters() {
  filters.value = []
}

// Watch document_type changes
watch(() => formData.document_type, (newVal) => {
  if (newVal) {
    loadPageTypeFields(newVal)
  } else {
    pageTypeFields.value = []
    filters.value = []
  }
})

watch(() => props.show, (newVal) => {
  if (newVal) {
    if (props.values) {
      formData.document_type = props.values.document_type || ''
      formData.label = props.values.label || ''
      formData.quick_list_filter = props.values.quick_list_filter || ''
      formData.name = props.values.name || ''
      
      // Load existing filters
      if (props.values.quick_list_filter) {
        try {
          const parsedFilters = JSON.parse(props.values.quick_list_filter)
          filters.value = parsedFilters.map((f: any) => ({
            fieldname: f[1],
            condition: f[2],
            value: f[3]
          }))
        } catch (e) {
          filters.value = []
        }
      } else {
        filters.value = []
      }
      
      // Load fields for editing
      if (props.values.document_type) {
        loadPageTypeFields(props.values.document_type)
      }
    } else {
      formData.document_type = ''
      formData.label = ''
      formData.quick_list_filter = ''
      formData.name = ''
      filters.value = []
      pageTypeFields.value = []
    }
  }
}, { immediate: true })

function handleSubmit() {
  if (!formData.document_type) {
    message.error(t('Please select a PageType'))
    return false
  }
  
  // Build filter array
  const filterArray = filters.value
    .filter(f => f.fieldname && f.value)
    .map(f => [formData.document_type, f.fieldname, f.condition, f.value])
  
  const data = {
    ...formData,
    label: formData.label || formData.document_type,
    quick_list_filter: JSON.stringify(filterArray)
  }
  
  if (!editing.value && !data.name) {
    data.name = `quick_list-${data.label}-${Math.random().toString(36).substring(2, 12)}`
  }
  
  emit('submit', data)
  visible.value = false
  return true
}

function handleCancel() {
  visible.value = false
}
</script>

<style scoped>
.dialog-content {
  padding: 16px 0;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-field {
  margin-bottom: 16px;
}

.field-label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.filter-section {
  margin-top: 16px;
}

.filters-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-field {
  width: 180px;
}

.filter-condition {
  width: 100px;
}

.filter-value {
  flex: 1;
}

.add-filter-btn {
  width: 100%;
}
</style>
