<template>
  <n-space align="center">
    <!-- 上一个按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="goToPrev"
      :disabled="loading || fetching || !hasPrev"
      :title="t('Previous')"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:chevron-left" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 下一个按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="goToNext"
      :disabled="loading || fetching || !hasNext"
      :title="t('Next')"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:chevron-right" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 侧边栏位置切换按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('toggle-sidebar-position')"
      :title="sidebarPosition === 'left' ? '切换到右侧' : '切换到左侧'"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon :icon="sidebarPosition === 'left' ? 'fluent:panel-right-16-regular' : 'fluent:panel-left-16-regular'" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 刷新按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('refresh')"
      :disabled="loading || isNew"
      :title="t('Refresh')"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:refresh" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 删除按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('delete')"
      :disabled="loading || isNew"
      :title="t('Delete')"
      class="header-action-btn delete-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:trash" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 返回按钮 -->
    <n-button type="default" size="medium" @click="$emit('go-back')" :disabled="loading">
      <template #icon>
        <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
      </template>
      {{ t('Back') }}
    </n-button>
    
    <!-- 保存按钮 -->
    <n-button 
      type="primary" 
      size="medium" 
      :disabled="loading" 
      @click="$emit('save')" 
      v-if="canEdit && (!isSubmittable || pageStatus === 0 || pageStatus === -1)" 
      class="save-btn-brand"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:check" />
        </n-icon>
      </template>
      {{ t('Save') }}
    </n-button>
    
    <!-- 提交按钮 -->
    <n-button 
      type="primary" 
      size="medium" 
      :disabled="loading || isNew" 
      @click="$emit('submit')" 
      v-if="isSubmittable && pageStatus === 0" 
      class="submit-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:send" />
        </n-icon>
      </template>
      {{ t('Submit') }}
    </n-button>
    
    <!-- 取消按钮 -->
    <n-button 
      type="error" 
      size="medium" 
      :disabled="loading" 
      @click="$emit('cancel-doc')" 
      v-if="isSubmittable && pageStatus === 1" 
      ghost
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:x" />
        </n-icon>
      </template>
      {{ t('Cancel') }}
    </n-button>
  </n-space>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NSpace, NIcon } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { usePageTypeSlug } from '@/shared/utils/slug'
import { getRecords } from '@/shared/api/common'

interface Props {
  entity: string
  id: string
  record?: any
  canEdit: boolean
  loading: boolean
  isSubmittable?: boolean
  pageStatus?: number
  sidebarPosition?: 'left' | 'right'
}

interface Emits {
  (e: 'toggle-sidebar-position'): void
  (e: 'refresh'): void
  (e: 'delete'): void
  (e: 'go-back'): void
  (e: 'save'): void
  (e: 'submit'): void
  (e: 'cancel-doc'): void
}

const props = withDefaults(defineProps<Props>(), {
  sidebarPosition: 'left',
  record: () => ({}),
  isSubmittable: false,
  pageStatus: -1
})

defineEmits<Emits>()

const route = useRoute()
const router = useRouter()
const { pagetypeSlug } = usePageTypeSlug(route)

const isNew = computed(() => props.id === 'new' || props.id.startsWith('new-'))

const listStateKey = computed(() => `list-state:${props.entity}`)
const rowNames = ref<string[]>([])
const fetching = ref(false)
const loadedStart = ref(0)
const hasMoreNext = ref(false)
const hasMorePrev = ref(false)
const pageSize = parseInt(localStorage.getItem('itemsPerPage') || '10')

const currentIndex = computed(() => {
  if (!props.id || rowNames.value.length === 0) return -1
  return rowNames.value.indexOf(props.id)
})

const hasPrev = computed(() => {
  if (isNew.value) return false
  return currentIndex.value > 0 || hasMorePrev.value
})

const hasNext = computed(() => {
  if (isNew.value || currentIndex.value < 0) return false
  return currentIndex.value < rowNames.value.length - 1 || hasMoreNext.value
})

function readListState(): any | null {
  const saved = sessionStorage.getItem(listStateKey.value)
  if (!saved) return null
  try { return JSON.parse(saved) } catch { return null }
}

function loadRowNames() {
  const state = readListState()
  if (!state?.rowNames?.length) return
  rowNames.value = state.rowNames
  loadedStart.value = ((state.page || 1) - 1) * pageSize
  hasMorePrev.value = loadedStart.value > 0
  hasMoreNext.value = state.rowNames.length >= pageSize
}

function buildApiFilters(filters: Record<string, any>): any[] {
  if (!filters) return []
  return Object.entries(filters)
    .filter(([, v]) => v !== null && v !== undefined && v !== '' && !(Array.isArray(v) && v.length === 0))
    .map(([k, v]) => typeof v === 'string' ? [k, 'like', `%${v}%`] : Array.isArray(v) ? [k, 'in', v] : [k, '=', v])
}

async function fetchPage(direction: 'next' | 'prev'): Promise<string[]> {
  const state = readListState()
  if (!state || state.searchQuery) return []

  const orderBy = `${state.sortBy || 'modified'} ${state.sortOrder || 'desc'}`
  const filters = buildApiFilters(state.filters)
  const ps = pageSize

  let limitStart: number, limitLength: number
  if (direction === 'next') {
    limitStart = loadedStart.value + rowNames.value.length
    limitLength = ps
  } else {
    limitLength = Math.min(ps, loadedStart.value)
    limitStart = loadedStart.value - limitLength
    if (limitLength <= 0) return []
  }

  const res = await getRecords(props.entity, filters, ['name'], orderBy, limitStart, limitLength)
  if (!res.success || !res.data?.length) {
    if (direction === 'next') hasMoreNext.value = false
    else hasMorePrev.value = false
    return []
  }

  const newNames = res.data.map((r: any) => r.name)
  if (direction === 'next') {
    rowNames.value = [...rowNames.value, ...newNames]
    hasMoreNext.value = newNames.length >= ps
  } else {
    rowNames.value = [...newNames, ...rowNames.value]
    loadedStart.value -= newNames.length
    hasMorePrev.value = loadedStart.value > 0
  }

  try {
    state.rowNames = rowNames.value
    sessionStorage.setItem(listStateKey.value, JSON.stringify(state))
  } catch {}

  return newNames
}

function navigateTo(name: string) {
  router.push({
    name: 'PageTypeDetail',
    params: { entity: pagetypeSlug.value, id: name },
    state: { _listPage: history.state?._listPage || 1 }
  })
}

async function goToPrev() {
  if (fetching.value) return
  if (currentIndex.value > 0) {
    navigateTo(rowNames.value[currentIndex.value - 1])
  } else if (hasMorePrev.value) {
    fetching.value = true
    try {
      const newNames = await fetchPage('prev')
      if (newNames.length) {
        const idx = rowNames.value.indexOf(props.id)
        if (idx > 0) navigateTo(rowNames.value[idx - 1])
      }
    } finally { fetching.value = false }
  }
}

async function goToNext() {
  if (fetching.value) return
  if (currentIndex.value >= 0 && currentIndex.value < rowNames.value.length - 1) {
    navigateTo(rowNames.value[currentIndex.value + 1])
  } else if (hasMoreNext.value) {
    fetching.value = true
    try {
      const newNames = await fetchPage('next')
      if (newNames.length) {
        const idx = currentIndex.value + 1
        if (idx < rowNames.value.length) navigateTo(rowNames.value[idx])
      }
    } finally { fetching.value = false }
  }
}

onMounted(() => {
  loadRowNames()
})
</script>

<style scoped>
/* 头部操作按钮统一样式 */
.header-action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 删除按钮悬浮时使用红色 */
.header-action-btn.delete-btn:hover:not(:disabled) {
  background: #ef4444 !important;
  border-color: #ef4444 !important;
  color: white !important;
}

.header-action-btn.delete-btn:hover:not(:disabled) :deep(.n-button__border),
.header-action-btn.delete-btn:hover:not(:disabled) :deep(.n-button__state-border) {
  border-color: #ef4444 !important;
}

/* 保存按钮 - 使用柔和的品牌色系，与列表页创建按钮一致 */
.save-btn-brand {
  background: #e6f8f0 !important;
  border: 1px solid #1fc76f !important;
  color: #0d684b !important;
}

.save-btn-brand :deep(.n-button__border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:hover {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15) !important;
}

.save-btn-brand:hover :deep(.n-button__border),
.save-btn-brand:hover :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:focus {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 0 0 2px rgba(31, 199, 111, 0.2) !important;
}

.save-btn-brand:focus :deep(.n-button__border),
.save-btn-brand:focus :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:active {
  background: #1fc76f !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: white !important;
  box-shadow: 0 1px 4px rgba(31, 199, 111, 0.2) !important;
}

.save-btn-brand:active :deep(.n-button__border),
.save-btn-brand:active :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:disabled {
  background: #f1f5f9 !important;
  border: 1px solid #e2e8f0 !important;
  border-color: #e2e8f0 !important;
  color: #94a3b8 !important;
  opacity: 0.6 !important;
  cursor: not-allowed !important;
}

.save-btn-brand:disabled :deep(.n-button__border),
.save-btn-brand:disabled :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}
</style>

