<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 || !canDeleteModel"
      :title="t('Delete')"
      class="header-action-btn delete-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:trash" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 收藏(Like)按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="handleToggleLike"
      :disabled="loading || isNew"
      :loading="likeLoading"
      :title="isLiked ? t('Unlike') : t('Like')"
      class="header-action-btn like-action-btn"
      :class="{ 'is-liked': isLiked }"
    >
      <template #icon>
        <n-icon>
          <Icon :icon="isLiked ? 'tabler:heart-filled' : 'tabler:heart'" />
        </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-dropdown
      :options="menuOptions"
      trigger="click"
      :render-icon="renderMenuIcon"
      @select="handleMenuSelect"
    >
      <n-button 
        type="default" 
        size="medium"
        :title="t('More')"
        class="header-action-btn"
      >
        <template #icon>
          <n-icon>
            <Icon icon="tabler:dots" />
          </n-icon>
        </template>
      </n-button>
    </n-dropdown>

    <!-- 保存按钮 -->
    <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-pg')" 
      v-if="isSubmittable && pageStatus === 1" 
      ghost
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:x" />
        </n-icon>
      </template>
      {{ t('Cancel') }}
    </n-button>

    <!-- 重命名对话框 -->
    <n-modal
      v-model:show="showRenameDialog"
      preset="dialog"
      :title="t('Rename')"
      :positive-text="t('OK')"
      :negative-text="t('Cancel')"
      :positive-button-props="{ type: 'primary' }"
      :loading="renaming"
      @positive-click="handleRenameConfirm"
      style="width: 450px;"
    >
      <n-form ref="renameFormRef" :model="renameForm" :rules="renameRules" label-placement="top">
        <n-form-item :label="t('New Name')" path="newName">
          <n-input v-model:value="renameForm.newName" :placeholder="t('Enter new name')" />
        </n-form-item>
        <n-form-item :label="t('Merge with existing')" path="merge">
          <n-checkbox v-model:checked="renameForm.merge">
            <span>{{ t('Merge with existing') }}</span>
            <n-text depth="3" style="margin-left: 4px;">({{ t('This cannot be undone') }})</n-text>
          </n-checkbox>
        </n-form-item>
      </n-form>
    </n-modal>

    <!-- Email Compose Drawer -->
    <EmailComposeModal ref="emailComposeRef" />
  </n-space>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NSpace, NIcon, NDropdown, NModal, NForm, NFormItem, NInput, NCheckbox, NText, useMessage, type FormInst, type FormRules, type DropdownOption } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { usePageTypeSlug } from '@/shared/utils/slug'
import { getRecords, renameRecord, duplicateRecord } from '@/shared/api/common'
import { toggleLike as toggleLikeApi } from '@/shared/api/timeline'
import { useAuthStore } from '@/shared/stores/auth'
import EmailComposeModal from '@/shared/components/EmailComposeModal.vue'

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

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-pg'): void
  (e: 'rename', newName: string): void
  (e: 'duplicate', newName: string): void
}

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

const emit = defineEmits<Emits>()

const message = useMessage()

const authStore = useAuthStore()

// ===== Like (收藏) =====
const likeLoading = ref(false)
const currentUser = computed(() => authStore.user?.username || authStore.user?.name || '')

// ===== Email Compose =====
const emailComposeRef = ref<InstanceType<typeof EmailComposeModal> | null>(null)

function openEmailCompose() {
  // Try to get email from record for pre-filling
  const emailField = props.record?.email_id || props.record?.email || ''
  emailComposeRef.value?.open({
    referencePagetype: props.entity,
    referenceName: props.id,
    defaultRecipients: emailField || undefined,
  })
}
const likedBy = computed<string[]>(() => {
  const raw = props.record?._liked_by
  if (!raw) return []
  if (typeof raw === 'string') { try { return JSON.parse(raw) } catch { return [] } }
  return Array.isArray(raw) ? raw : []
})
const isLiked = computed(() => likedBy.value.includes(currentUser.value))

async function handleToggleLike() {
  if (isNew.value || likeLoading.value) return
  likeLoading.value = true
  try {
    await toggleLikeApi(props.entity, props.id, isLiked.value ? 'No' : 'Yes')
    // Refresh parent to update _liked_by field
    emit('refresh')
  } catch (err: any) {
    message.error(err?.message || t('Failed to toggle like'))
  } finally {
    likeLoading.value = false
  }
}

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

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

const canDeleteModel = computed(() => props.canDelete === true)

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 }
  }
}

// ===== 重命名功能 =====
// 判断是否可以重命名：与旧版 can_rename() 对齐
// 旧版: frm.perm[0].write && frm.meta.allow_rename && !frm.pg.__islocal
const canRename = computed(() => {
  if (isNew.value) return false
  if (!props.canEdit) return false
  // pageMeta.allow_rename 是后端 meta 中的字段
  return !!(props.pageMeta?.allow_rename)
})

// 三点菜单选项
const menuOptions = computed<DropdownOption[]>(() => {
  const options: DropdownOption[] = []
  // 重复 - 对齐旧版: jingrow.boot.user.can_create.includes(pagetype) && !meta.allow_copy
  if (!isNew.value && props.canEdit && !props.pageMeta?.allow_copy) {
    options.push({
      label: t('Duplicate'),
      key: 'duplicate',
      icon: 'tabler:copy'
    })
  }
  if (canRename.value) {
    options.push({
      label: t('Rename'),
      key: 'rename',
      icon: 'tabler:edit'
    })
  }
  // Email - show for saved records (not new)
  if (!isNew.value) {
    options.push({
      label: t('New Email'),
      key: 'email',
      icon: 'tabler:mail'
    })
  }
  return options
})

function renderMenuIcon(option: DropdownOption) {
  const iconName = option.icon as string
  if (!iconName) return null
  return h(NIcon, null, { default: () => h(Icon, { icon: iconName }) })
}

function handleMenuSelect(key: string) {
  if (key === 'rename') {
    openRenameDialog()
  } else if (key === 'duplicate') {
    handleDuplicate()
  } else if (key === 'email') {
    openEmailCompose()
  }
}

// ===== 重复功能 =====
const duplicating = ref(false)

async function handleDuplicate() {
  if (duplicating.value || isNew.value) return
  duplicating.value = true
  try {
    const result = await duplicateRecord(props.entity, props.id)
    if (result.success && result.data) {
      // 与旧版对齐：不直接保存，而是将副本数据存入 sessionStorage，
      // 导航到新建页面，让用户修改后手动保存
      const storageKey = `duplicate:${props.entity}`
      try {
        sessionStorage.setItem(storageKey, JSON.stringify(result.data))
      } catch {}
      emit('duplicate', '')
    } else {
      message.error(result.message || t('Failed to duplicate record'))
    }
  } catch (err: any) {
    message.error(err?.message || t('Failed to duplicate record'))
  } finally {
    duplicating.value = false
  }
}

// 重命名对话框
const showRenameDialog = ref(false)
const renaming = ref(false)
const renameFormRef = ref<FormInst | null>(null)
const renameForm = ref({
  newName: '',
  merge: false
})
const renameRules: FormRules = {
  newName: [
    { required: true, message: t('New name is required'), trigger: 'blur' }
  ]
}

function openRenameDialog() {
  renameForm.value.newName = props.id
  renameForm.value.merge = false
  showRenameDialog.value = true
}

async function handleRenameConfirm() {
  // 验证表单
  try {
    await renameFormRef.value?.validate()
  } catch {
    return false
  }

  const { newName, merge } = renameForm.value
  if (!newName || newName === props.id) {
    message.info(t('No changes made'))
    return false
  }

  // 如果勾选合并，弹出确认
  if (merge) {
    // 简单确认（naive-ui modal 内不方便再弹 confirm，直接执行后端会校验）
  }

  renaming.value = true
  try {
    const result = await renameRecord(props.entity, props.id, newName, merge)
    if (result.success) {
      showRenameDialog.value = false
      // 通知父组件重命名完成，跳转到新名称
      emit('rename', result.data || newName)
    } else {
      message.error(result.message || t('Failed to rename document'))
      return false
    }
  } catch (err: any) {
    message.error(err?.message || t('Failed to rename document'))
    return false
  } finally {
    renaming.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;
}

/* Like按钮已收藏状态 - 与列表页风格一致：图标红色+浅红背景 */
.header-action-btn.like-action-btn.is-liked {
  background: #fef2f2 !important;
}
.header-action-btn.like-action-btn.is-liked :deep(.n-icon) {
  color: #ef4444;
}
.header-action-btn.like-action-btn.is-liked :deep(.n-button__border),
.header-action-btn.like-action-btn.is-liked :deep(.n-button__state-border) {
  border-color: #fecaca !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>

