<template>
  <n-space align="center">
    <!-- 前往按钮：子表不显示，单例显示“前往”，其他显示“前往列表" -->
    <n-button 
      type="default" 
      size="medium" 
      @click="goToList"
      v-if="!isNew && !isTable"
      :title="goToLabel"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:list" />
        </n-icon>
      </template>
      {{ goToLabel }}
    </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-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" 
      class="save-btn-brand"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:check" />
        </n-icon>
      </template>
      {{ t('Save') }}
    </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>
  </n-space>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, h } from 'vue'
import { 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 axios from 'axios'
import { t } from '@/shared/i18n'
import { pageTypeToSlug } from '@/shared/utils/slug'
import { renameRecord } from '@/shared/api/common'
import { getCurrentLocale } from '@/shared/i18n'

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

interface Emits {
  (e: 'toggle-sidebar-position'): void
  (e: 'refresh'): void
  (e: 'delete'): void
  (e: 'go-back'): void
  (e: 'save'): void
  (e: 'rename', newName: string): void
}

const props = withDefaults(defineProps<Props>(), {
  sidebarPosition: 'left',
  record: () => ({})
})

const emit = defineEmits<Emits>()
const router = useRouter()
const message = useMessage()

// 计算是否为新建记录
const isNew = computed(() => {
  const idValue = props.id
  return idValue === 'new' || idValue.startsWith('new-')
})

// 计算是否为子表（istable=1），子表没有独立的列表页
const isTable = computed(() => {
  return !!(props.record?.istable)
})

// 计算是否为单例（issingle=1），单例没有列表页，只有一条记录
const isSingle = computed(() => {
  return !!(props.record?.issingle)
})

// 按钮文字：单例显示“前往 {name}”，其他显示“前往 {name} 列表"
const goToLabel = computed(() => {
  if (isSingle.value) {
    return t('Go to {0}').replace('{0}', t(props.id))
  }
  return t('Go to {0} List').replace('{0}', t(props.id))
})

// 从 localStorage 读取侧边栏位置（如果父组件没有传入）
const sidebarPosition = ref<'left' | 'right'>(props.sidebarPosition || 'left')

// 监听 props 变化
watch(() => props.sidebarPosition, (newPos) => {
  if (newPos) {
    sidebarPosition.value = newPos
  }
}, { immediate: true })

onMounted(() => {
  // 如果没有传入 sidebarPosition，尝试从 localStorage 读取
  if (!props.sidebarPosition) {
    const savedPosition = localStorage.getItem('jingrow-sidebar-position')
    if (savedPosition === 'left' || savedPosition === 'right') {
      sidebarPosition.value = savedPosition
    }
  }
})

const goToList = () => {
  if (props.id) {
    const entitySlug = pageTypeToSlug(props.id)
    const routeData = router.resolve({
      name: 'PageTypeList',
      params: { entity: entitySlug }
    })
    window.open(routeData.href, '_blank')
  }
}

// ===== 重命名功能 =====
// PageType 的 allow_rename 默认为 1，非新建状态且有编辑权限时可重命名
const canRename = computed(() => {
  if (isNew.value) return false
  if (!props.canEdit) return false
  return true // PageType 默认允许重命名
})

// ===== 翻译功能 =====
const translationRecordName = ref('')
const checkingTranslation = ref(false)

async function checkTranslation(): Promise<string | null> {
  if (isNew.value || !props.id) return null
  checkingTranslation.value = true
  try {
    const response = await axios.get('/api/data/Translation', {
      params: {
        filters: JSON.stringify({ source_text: props.id }),
        fields: JSON.stringify(['name'])
      }
    })
    const data = response.data?.data || []
    if (data.length > 0) {
      return data[0].name
    }
    return null
  } catch {
    return null
  } finally {
    checkingTranslation.value = false
  }
}

function goToTranslation() {
  if (!props.id || isNew.value) return

  checkingTranslation.value = true
  checkTranslation().then(name => {
    checkingTranslation.value = false
    translationRecordName.value = name || ''
    if (name) {
      // 已有翻译，跳转到详情页
      const slug = pageTypeToSlug('Translation')
      window.open(`/app/${slug}/${name}`, '_blank')
    } else {
      // 没有翻译，跳转到新建页面，使用 sessionStorage 预填数据
      const slug = pageTypeToSlug('Translation')
      const randomStr = Math.random().toString(36).substring(2, 12)
      const tempName = `new-${slug}-${randomStr}`
      // 获取当前语言（优先用户语言，其次系统语言）
      const currentLang = getCurrentLocale()
      // 使用 sessionStorage 传递预填数据（与复制功能保持一致）
      sessionStorage.setItem(`duplicate:Translation`, JSON.stringify({
        source_text: props.id,
        language: currentLang || 'zh'
      }))
      window.open(`/app/${slug}/${tempName}`, '_blank')
    }
  })
}

// 三点菜单选项
const menuOptions = computed<DropdownOption[]>(() => {
  const options: DropdownOption[] = []
  if (canRename.value) {
    options.push({
      label: t('Rename'),
      key: 'rename',
      icon: 'tabler:edit'
    })
  }
  if (!isNew.value) {
    options.push({
      label: t('Translation'),
      key: 'translation',
      icon: 'tabler:language'
    })
  }
  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 === 'translation') {
    goToTranslation()
  }
}

// 重命名对话框
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
  }

  renaming.value = true
  try {
    const result = await renameRecord(props.entity, props.id, newName, merge)
    if (result.success) {
      showRenameDialog.value = false
      emit('rename', 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
  }
}
</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:not(:disabled) {
  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:not(:disabled) :deep(.n-button__border),
.save-btn-brand:hover:not(:disabled) :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>
