<template>
  <n-modal
    v-model:show="visible"
    preset="dialog"
    :title="editing ? t('Edit Shortcut') : t('Add Shortcut')"
    :positive-text="editing ? t('Save') : t('Add')"
    :negative-text="t('Cancel')"
    @positive-click="handleSubmit"
    @negative-click="handleCancel"
    style="width: 600px;"
  >
    <div class="dialog-content">
      <div class="form-row">
        <div class="form-field">
          <label class="field-label">
            {{ t('Type') }}
            <span class="required">*</span>
          </label>
          <n-select
            v-model:value="formData.type"
            :options="typeOptions"
            placeholder=""
            @update:value="handleTypeChange"
          />
        </div>
        
        <!-- Dynamic Link field (for non-URL types) -->
        <div v-if="formData.type !== 'URL'" class="form-field">
          <LinkField
            v-model="formData.link_to"
            :options="linkToOptions"
            :label="t('Link To')"
            :required="true"
            placeholder=""
            :get-query="getLinkQuery"
          />
        </div>
        
        <!-- URL field (for URL type) -->
        <div v-else class="form-field">
          <label class="field-label">
            {{ t('URL') }}
            <span class="required">*</span>
          </label>
          <n-input
            v-model:value="formData.url"
            placeholder=""
          />
        </div>
      </div>
      
      <!-- Label field -->
      <div class="form-field">
        <label class="field-label">{{ t('Label') }}</label>
        <n-input
          v-model:value="formData.label"
          placeholder=""
        />
      </div>
      
      <!-- PageType View selector -->
      <div v-if="formData.type === 'PageType' && formData.link_to" class="form-field">
        <label class="field-label">{{ t('PageType View') }}</label>
        <n-select
          v-model:value="formData.pg_view"
          :options="viewOptions"
          placeholder=""
        />
        <p class="field-description">{{ t('Which view of the associated PageType should this shortcut take you to?') }}</p>
      </div>
      
      <!-- Count Filter Section -->
      <div v-if="formData.type === 'PageType' && formData.link_to">
        <n-divider>{{ t('Count Filter') }}</n-divider>
        
        <div v-if="statsFilters.length > 0" class="filters-list">
          <div v-for="(filter, index) in statsFilters" :key="index" class="stats-filter-row">
            <n-select
              v-model:value="filter.fieldname"
              :options="statsFieldOptions"
              size="small"
              placeholder=""
              class="filter-field-select"
            />
            <n-select
              v-model:value="filter.condition"
              :options="conditionOptions"
              size="small"
              placeholder=""
              class="filter-condition-select"
            />
            <n-input
              v-model:value="filter.value"
              size="small"
              placeholder=""
              class="filter-value-input"
            />
            <n-button 
              size="small" 
              quaternary 
              type="error" 
              @click="removeStatsFilter(index)"
              class="filter-remove-btn"
            >
              <template #icon>
                <Icon icon="mdi:close" />
              </template>
            </n-button>
          </div>
        </div>
        
        <div class="add-filter-link">
          <a href="javascript:void(0)" @click="addStatsFilter">
            + {{ t('Add Filter') }}
          </a>
          <a 
            v-if="statsFilters.length > 0" 
            href="javascript:void(0)" 
            @click="clearStatsFilters"
            class="clear-link"
          >
            {{ t('Clear Filters') }}
          </a>
        </div>
      </div>
      
      <n-divider>{{ t('Count Customizations') }}</n-divider>
      
      <div class="form-row">
        <div class="form-field">
          <label class="field-label">{{ t('Color') }}</label>
          <n-select
            v-model:value="formData.color"
            :options="colorOptions"
            placeholder=""
          >
            <template #render-label="{ option }">
              <div class="color-option">
                <span class="color-box" :style="{ backgroundColor: getColorValue(option.value as string) }"></span>
                {{ option.label }}
              </div>
            </template>
          </n-select>
        </div>
        
        <div class="form-field">
          <label class="field-label">{{ t('Format') }}</label>
          <n-input
            v-model:value="formData.format"
            placeholder=""
          />
          <p class="field-description">{{ t('Use {} as placeholder for count') }}</p>
        </div>
      </div>
      
      <div class="form-field">
        <label class="field-label">{{ t('Icon') }}</label>
        <div class="upload-section">
          <n-upload
            :max="1"
            accept="image/*"
            :default-file-list="iconFileList"
            @change="handleIconChange"
            list-type="image-card"
            :show-file-list="true"
          >
            <n-button size="small" secondary>
              <template #icon>
                <Icon icon="mdi:upload" />
              </template>
              {{ t('Upload') }}
            </n-button>
          </n-upload>
          <p class="field-description">{{ t('Upload custom icon, supports png/jpg, recommended size: 100x100') }}</p>
        </div>
      </div>
    </div>
  </n-modal>
</template>

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

const props = defineProps<{
  show: boolean
  values?: {
    type?: string
    label?: string
    link_to?: string
    url?: string
    pg_view?: string
    color?: string
    format?: string
    stats_filter?: string
    icon?: 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 typeOptions = computed(() => [
  { label: t('PageType'), value: 'PageType' },
  { label: t('Report'), value: 'Report' },
  { label: t('Page'), value: 'Page' },
  { label: t('Dashboard'), value: 'Dashboard' },
  { label: t('URL'), value: 'URL' }
])

const viewOptions = computed(() => [
  { label: t('List'), value: 'List' },
  { label: t('Report Builder'), value: 'Report Builder' },
  { label: t('Dashboard'), value: 'Dashboard' },
  { label: t('Tree'), value: 'Tree' },
  { label: t('New'), value: 'New' },
  { label: t('Calendar'), value: 'Calendar' },
  { label: t('Kanban'), value: 'Kanban' }
])

const colorOptions = computed(() => [
  { label: t('Grey'), value: 'Grey' },
  { label: t('Green'), value: 'Green' },
  { label: t('Red'), value: 'Red' },
  { label: t('Orange'), value: 'Orange' },
  { label: t('Pink'), value: 'Pink' },
  { label: t('Yellow'), value: 'Yellow' },
  { label: t('Blue'), value: 'Blue' },
  { label: t('Cyan'), value: 'Cyan' }
])

const formData = reactive({
  type: 'PageType',
  label: '',
  link_to: '',
  url: '',
  pg_view: 'List',
  color: 'Grey',
  format: '',
  icon: '',
  name: ''
})

const statsFilters = ref<Array<{ fieldname: string; condition: string; value: string }>>([])
const statsFieldOptions = ref<Array<{ label: string; value: string }>>([
  { label: 'ID', value: 'name' }
])

const conditionOptions = [
  { label: '=', value: '=' },
  { label: '!=', value: '!=' },
  { label: '>', value: '>' },
  { label: '<', value: '<' },
  { label: 'like', value: 'like' }
]

const iconFileList = ref<UploadFileInfo[]>([])

// Dynamic link options based on type
const linkToOptions = computed(() => {
  switch (formData.type) {
    case 'PageType':
      return 'PageType'
    case 'Report':
      return 'Report'
    case 'Page':
      return 'Page'
    case 'Dashboard':
      return 'Dashboard'
    default:
      return 'PageType'
  }
})

// Custom query for link field
function getLinkQuery() {
  if (formData.type === 'PageType') {
    return {
      filters: {
        issingle: 0,
        istable: 0
      }
    }
  }
  return {}
}

function getColorValue(color: string): string {
  const colorMap: Record<string, string> = {
    'Grey': '#808080',
    'Green': '#28a745',
    'Red': '#dc3545',
    'Orange': '#fd7e14',
    'Pink': '#e83e8c',
    'Yellow': '#ffc107',
    'Blue': '#007bff',
    'Cyan': '#17a2b8'
  }
  return colorMap[color] || '#808080'
}

function handleTypeChange() {
  formData.link_to = ''
  formData.url = ''
  statsFilters.value = []
}

function addStatsFilter() {
  statsFilters.value.push({
    fieldname: 'name',
    condition: '=',
    value: ''
  })
}

function removeStatsFilter(index: number) {
  statsFilters.value.splice(index, 1)
}

function clearStatsFilters() {
  statsFilters.value = []
}

function handleIconChange({ fileList }: { fileList: UploadFileInfo[] }) {
  iconFileList.value = fileList
  if (fileList.length > 0 && fileList[0].url) {
    formData.icon = fileList[0].url
  } else {
    formData.icon = ''
  }
}

// Reset form when dialog opens
watch(() => props.show, (newVal) => {
  if (newVal) {
    if (props.values) {
      formData.type = props.values.type || 'PageType'
      formData.label = props.values.label || ''
      formData.link_to = props.values.link_to || ''
      formData.url = props.values.url || ''
      formData.pg_view = props.values.pg_view || 'List'
      formData.color = props.values.color || 'Grey'
      formData.format = props.values.format || ''
      formData.icon = props.values.icon || ''
      formData.name = props.values.name || ''
      
      // Parse stats_filter JSON to filters array
      if (props.values.stats_filter) {
        try {
          const parsed = JSON.parse(props.values.stats_filter)
          if (Array.isArray(parsed)) {
            statsFilters.value = parsed.map((f: any) => ({
              fieldname: f[1] || 'name',
              condition: f[2] || '=',
              value: f[3] || ''
            }))
          }
        } catch (e) {
          statsFilters.value = []
        }
      } else {
        statsFilters.value = []
      }
      
      if (props.values.icon) {
        iconFileList.value = [{
          id: 'existing',
          name: 'icon',
          status: 'finished',
          url: props.values.icon
        }]
      } else {
        iconFileList.value = []
      }
    } else {
      formData.type = 'PageType'
      formData.label = ''
      formData.link_to = ''
      formData.url = ''
      formData.pg_view = 'List'
      formData.color = 'Grey'
      formData.format = ''
      formData.icon = ''
      formData.name = ''
      statsFilters.value = []
      iconFileList.value = []
    }
  }
}, { immediate: true })

function handleSubmit() {
  // Validation
  if (formData.type === 'URL') {
    if (!formData.url) {
      message.error(t('Please enter URL'))
      return false
    }
  } else {
    if (!formData.link_to) {
      message.error(t('Please select link target'))
      return false
    }
  }
  
  // Convert filters array to JSON format
  let stats_filter = ''
  if (statsFilters.value.length > 0) {
    const filterArray = statsFilters.value
      .filter(f => f.fieldname && f.value)
      .map(f => [formData.link_to, f.fieldname, f.condition, f.value])
    stats_filter = JSON.stringify(filterArray)
  }
  
  const data = {
    ...formData,
    stats_filter,
    label: formData.label || formData.link_to || 'Shortcut'
  }
  
  if (!editing.value && !data.name) {
    data.name = `shortcut-${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;
}

.required {
  color: #e03131;
  margin-left: 2px;
}

.field-description {
  margin: 4px 0 0 0;
  font-size: 12px;
  color: #999;
}

.color-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-box {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.filters-list {
  margin-bottom: 12px;
}

.stats-filter-row {
  display: grid;
  grid-template-columns: 160px 120px 1fr auto;
  gap: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.filter-field-select {
  min-width: 160px;
}

.filter-condition-select {
  min-width: 120px;
}

.filter-value-input {
  flex: 1;
}

.filter-remove-btn {
  min-width: 32px;
}

.add-filter-link {
  margin-top: 8px;
  display: flex;
  gap: 16px;
}

.add-filter-link a {
  color: #18a058;
  text-decoration: none;
  font-size: 13px;
}

.add-filter-link a:hover {
  text-decoration: underline;
}

.add-filter-link .clear-link {
  color: #666;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>
