<template>
  <n-modal
    v-model:show="visible"
    preset="dialog"
    :title="editing ? t('Edit Card') : t('Add Card')"
    :positive-text="editing ? t('Save') : t('Add')"
    :negative-text="t('Cancel')"
    @positive-click="handleSubmit"
    @negative-click="handleCancel"
    style="width: 800px;"
  >
    <div class="dialog-content">
      <div class="form-field">
        <label class="field-label">{{ t('Label') }}</label>
        <n-input
          v-model:value="formData.label"
          :placeholder="t('Enter card label')"
        />
      </div>
      
      <div class="form-field">
        <label class="field-label">{{ t('Description') }}</label>
        <n-input
          v-model:value="formData.description"
          type="textarea"
          :rows="3"
          :placeholder="t('Enter description (optional)')"
        />
      </div>
      
      <n-divider>{{ t('Card Links') }}</n-divider>
      
      <div class="links-table">
        <div class="table-header">
          <span class="col-type">{{ t('Link Type') }}</span>
          <span class="col-link">{{ t('Link To') }}</span>
          <span class="col-label">{{ t('Label') }}</span>
          <span class="col-actions"></span>
        </div>
        
        <div v-for="(link, index) in formData.links" :key="index" class="table-row">
          <div class="col-type">
            <n-select
              v-model:value="link.link_type"
              :options="linkTypeOptions"
              size="small"
              @update:value="() => handleLinkTypeChange(index)"
            />
          </div>
          <div class="col-link">
            <LinkField
              v-model="link.link_to"
              :options="getLinkOptions(link.link_type)"
              :placeholder="t('Select')"
              :get-query="() => getLinkQuery(link.link_type)"
            />
          </div>
          <div class="col-label">
            <n-input
              v-model:value="link.label"
              size="small"
              :placeholder="t('Label')"
            />
          </div>
          <div class="col-actions">
            <n-button
              size="small"
              quaternary
              type="error"
              @click="removeLink(index)"
            >
              <template #icon>
                <Icon icon="mdi:close" />
              </template>
            </n-button>
          </div>
        </div>
        
        <div v-if="formData.links.length === 0" class="empty-row">
          {{ t('No Items Found') }}
        </div>
        
        <n-button
          class="add-link-btn"
          size="small"
          dashed
          @click="addLink"
        >
          <template #icon>
            <Icon icon="mdi:plus" />
          </template>
          {{ t('Add') }}
        </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 LinkField from './LinkField.vue'

interface CardLink {
  link_type: string
  link_to: string
  label: string
  icon?: string
}

const props = defineProps<{
  show: boolean
  values?: {
    label?: string
    description?: string
    links?: string | CardLink[]
    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 linkTypeOptions = [
  { label: 'PageType', value: 'PageType' },
  { label: 'Page', value: 'Page' },
  { label: 'Report', value: 'Report' }
]

const formData = reactive({
  label: '',
  description: '',
  links: [] as CardLink[],
  name: ''
})

function getLinkOptions(linkType: string): string {
  switch (linkType) {
    case 'PageType':
      return 'PageType'
    case 'Page':
      return 'Page'
    case 'Report':
      return 'Report'
    default:
      return 'PageType'
  }
}

function getLinkQuery(linkType: string) {
  if (linkType === 'PageType') {
    return {
      filters: {
        istable: 0
      }
    }
  }
  return {}
}

function handleLinkTypeChange(index: number) {
  formData.links[index].link_to = ''
}

function addLink() {
  formData.links.push({
    link_type: 'PageType',
    link_to: '',
    label: ''
  })
}

function removeLink(index: number) {
  formData.links.splice(index, 1)
}

// Parse links from values
function parseLinks(links: string | CardLink[] | undefined): CardLink[] {
  if (!links) return []
  if (typeof links === 'string') {
    try {
      return JSON.parse(links)
    } catch {
      return []
    }
  }
  return links
}

// Reset form when dialog opens
watch(() => props.show, (newVal) => {
  if (newVal) {
    if (props.values) {
      formData.label = props.values.label || ''
      formData.description = props.values.description || ''
      formData.links = parseLinks(props.values.links)
      formData.name = props.values.name || ''
    } else {
      formData.label = ''
      formData.description = ''
      formData.links = []
      formData.name = ''
    }
  }
}, { immediate: true })

function handleSubmit() {
  // Validation
  if (formData.links.length === 0) {
    message.error(t('You must add at least one link'))
    return false
  }
  
  // Validate each link
  for (let i = 0; i < formData.links.length; i++) {
    const link = formData.links[i]
    if (!link.link_type) {
      message.error(t('Link Type is required in row') + ` ${i + 1}`)
      return false
    }
    if (!link.link_to) {
      message.error(t('Link To is required in row') + ` ${i + 1}`)
      return false
    }
    // Auto-fill label if empty
    if (!link.label) {
      link.label = link.link_to
    }
  }
  
  const data = {
    label: formData.label,
    description: formData.description,
    links: JSON.stringify(formData.links),
    name: formData.name
  }
  
  if (!editing.value && !data.name) {
    data.name = `card-${formData.label || 'card'}-${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;
  overflow: visible;
}

:deep(.n-dialog__content) {
  overflow: visible !important;
}

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

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

.links-table {
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  overflow: visible;
}

.table-header {
  display: grid;
  grid-template-columns: 150px 1fr 150px 50px;
  gap: 12px;
  padding: 12px;
  background: #f8f8f8;
  font-weight: 500;
  font-size: 13px;
  color: #666;
}

.table-row {
  display: grid;
  grid-template-columns: 150px 1fr 150px 50px;
  gap: 12px;
  padding: 12px;
  border-top: 1px solid #e5e5e5;
  align-items: flex-start;
  overflow: visible;
  position: relative;
}

.table-row:hover {
  background: #fafafa;
}

.col-type,
.col-link,
.col-label,
.col-actions {
  display: flex;
  align-items: center;
}

.col-link {
  flex-direction: column;
  position: relative;
  overflow: visible;
}

.col-link :deep(.link-field) {
  margin-bottom: 0;
  width: 100%;
}

.col-actions {
  justify-content: center;
}

.empty-row {
  padding: 24px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.add-link-btn {
  margin: 12px;
  width: calc(100% - 24px);
}
</style>
