<template>
  <n-space align="center">
    <!-- 侧边栏位置切换按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('toggle-sidebar-position')"
      :title="sidebarPosition === 'left' ? t('Switch to Right') : t('Switch to 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>

    <!-- Whiteboard 按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="handleWhiteboard"
      :disabled="loading || isNew"
      v-if="!isNew"
      class="toolbar-btn whiteboard-btn"
    >
      <template #icon>
        <n-icon><Icon icon="tabler:chalkboard" /></n-icon>
      </template>
      {{ t('Open Whiteboard') }}
    </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
      v-if="menuOptions.length > 0"
      :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 } from 'naive-ui'
import type { DropdownOption, FormInst, FormRules } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { pageTypeToSlug } from '@/shared/utils/slug'
import { t } from '@/shared/i18n'
import { renameRecord, duplicateRecord } from '@/shared/api/common'

const props = defineProps<{
  entity: string
  id: string
  loading?: boolean
  isNew?: boolean
  canEdit?: boolean
  pageMeta?: any
  sidebarPosition?: string
}>()

const emit = defineEmits<{
  (e: 'refresh'): void
  (e: 'delete'): void
  (e: 'go-back'): void
  (e: 'toggle-sidebar-position'): void
  (e: 'save'): void
  (e: 'rename', newName: string): void
  (e: 'duplicate', newName: string): void
}>()

const router = useRouter()
const message = useMessage()
const sidebarPosition = ref(props.sidebarPosition || 'left')

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

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

onMounted(() => {
  if (!props.sidebarPosition) {
    const savedPosition = localStorage.getItem('jingrow-sidebar-position')
    if (savedPosition === 'left' || savedPosition === 'right') {
      sidebarPosition.value = savedPosition
    }
  }
})

// Whiteboard 按钮处理函数
function handleWhiteboard() {
  if (props.isNew) return
  const pagetype = pageTypeToSlug(props.entity)
  router.push({ name: 'WhiteboardEditor', query: { pagetype, id: props.id } })
}

// ===== 三点菜单 =====
const menuOptions = computed<DropdownOption[]>(() => {
  const options: DropdownOption[] = []
  if (!isNew.value && props.canEdit && !props.pageMeta?.allow_copy) {
    options.push({
      label: t('Duplicate'),
      key: 'duplicate',
      icon: 'tabler:copy' as any
    })
  }
  if (!isNew.value && props.canEdit && props.pageMeta?.allow_rename) {
    options.push({
      label: t('Rename'),
      key: 'rename',
      icon: 'tabler:edit' as any
    })
  }
  return options
})

function renderMenuIcon(option: DropdownOption) {
  const iconName = option.icon as any 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()
  }
}

// ===== 重复功能 =====
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) {
      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
  }

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

<style scoped>
.header-action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
}

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

.delete-btn:hover:not(:disabled) :deep(.n-button__border),
.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;
}

/* 工具栏按钮基础样式 */
.toolbar-btn {
  background: #f3f4f6 !important;
  color: #374151 !important;
  border: 1px solid rgba(0, 0, 0, 0.08) !important;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

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

.toolbar-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

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

/* Whiteboard 按钮 - 紫色系 */
.whiteboard-btn {
  background: #f3e8ff !important;
  color: #7c3aed !important;
  border-color: rgba(124, 58, 237, 0.2) !important;
}

.whiteboard-btn:hover:not(:disabled) {
  background: #ede9fe !important;
  color: #6d28d9 !important;
  border-color: rgba(124, 58, 237, 0.3) !important;
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.15);
}

.toolbar-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

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