<template>
  <n-popover
    trigger="click"
    placement="bottom-end"
    :show="showPopover"
    @update:show="handlePopoverUpdate"
    :show-arrow="false"
    :style="{ padding: 0 }"
    raw
  >
    <template #trigger>
      <n-button quaternary circle>
        <template #icon>
          <Icon icon="tabler:plus" :size="20" />
        </template>
      </n-button>
    </template>

    <div class="quick-create">
      <!-- Menu View -->
      <template v-if="view === 'menu'">
        <div class="qc-header">{{ t('Quick Create') }}</div>
        <div class="qc-menu">
          <div
            v-for="item in menuItems"
            :key="item.label"
            class="qc-menu-item"
            @click="selectPageType(item)"
          >
            <Icon :icon="item.icon" :size="18" />
            <span>{{ t(item.label) }}</span>
          </div>
        </div>
      </template>

      <!-- Form View -->
      <template v-else>
        <div class="qc-header">
          <n-button text size="small" @click="backToMenu">
            <template #icon><Icon icon="tabler:arrow-left" :size="16" /></template>
          </n-button>
          <span class="qc-header-title">{{ t('New {0}', [t(selectedLabel)]) }}</span>
          <n-button
            type="primary"
            size="small"
            :loading="submitting"
            @click="handleSubmit"
            class="save-btn-brand"
          >
            <template #icon><Icon icon="tabler:check" :size="14" /></template>
            {{ t('Save') }}
          </n-button>
        </div>

        <div v-if="loadingFields" class="qc-loading">
          <n-spin size="small" />
        </div>
        <div v-else class="qc-form">
          <div v-for="field in fields" :key="field.fieldname" class="qc-field">
            <FieldRenderer
              :df="field"
              :record="formData"
              :can-edit="true"
              :ctx="fieldCtx"
            />
          </div>
        </div>
      </template>
    </div>
  </n-popover>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { NPopover, NButton, NSpin, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import FieldRenderer from '@/core/pagetype/form/FieldRenderer.vue'
import { getQuickEntryFields, createRecord } from '../api/common'
import { createT, t } from '../i18n'

const message = useMessage()

const showPopover = ref(false)
const view = ref<'menu' | 'form'>('menu')
const selectedPageType = ref('')
const selectedLabel = ref('')
const fields = ref<any[]>([])
const formData = reactive<Record<string, any>>({})
const loadingFields = ref(false)
const submitting = ref(false)

// Context-aware translation: auto-injects selectedPageType as msgctxt
const t_ctx = createT(() => selectedPageType.value || null)

// Minimal ctx for FieldRenderer
const fieldCtx: Record<string, any> = {
  t: t_ctx,
  entity: '',
  getSelectOptions(field: any) {
    if (!field.options) return []
    return field.options.split('\n').filter((s: string) => s.trim() !== '').map((opt: string) => ({ label: t_ctx(opt), value: opt }))
  },
}

const menuItems = [
  { label: 'Activity', icon: 'tabler:activity' },
  { label: 'ToDo', icon: 'tabler:checklist' },
  { label: 'Knowledge Base', icon: 'tabler:book' },
  { label: 'Note', icon: 'tabler:note' },
]

const handlePopoverUpdate = (show: boolean) => {
  showPopover.value = show
}

const selectPageType = async (item: { label: string; icon: string }) => {
  selectedPageType.value = item.label
  selectedLabel.value = item.label
  fieldCtx.entity = item.label
  view.value = 'form'
  loadingFields.value = true

  // Reset form data
  Object.keys(formData).forEach(k => delete formData[k])

  const result = await getQuickEntryFields(item.label)
  if (result.success && result.data) {
    fields.value = result.data
    // Set defaults
    for (const field of result.data) {
      if (field.default) {
        if (field.fieldtype === 'Check') {
          formData[field.fieldname] = field.default ? 1 : 0
        } else if (field.fieldtype === 'Date' && field.default === 'Today') {
          formData[field.fieldname] = new Date().toISOString().split('T')[0]
        } else {
          formData[field.fieldname] = field.default
        }
      }
    }
  } else {
    message.error(result.message || t('Failed to load fields'))
  }
  loadingFields.value = false
}

const backToMenu = () => {
  view.value = 'menu'
  fields.value = []
  Object.keys(formData).forEach(k => delete formData[k])
}

const handleSubmit = async () => {
  // Validate required fields
  for (const field of fields.value) {
    if (field.reqd && !formData[field.fieldname]) {
      message.warning(t('{0} is required', [field.label]))
      return
    }
  }

  submitting.value = true
  try {
    // Convert Check boolean to int
    const data = { ...formData }
    for (const field of fields.value) {
      if (field.fieldtype === 'Check') {
        data[field.fieldname] = data[field.fieldname] ? 1 : 0
      }
    }

    const result = await createRecord(selectedPageType.value, data)
    if (result.success) {
      message.success(t('Created successfully'))
      nextTick(() => {
        showPopover.value = false
        backToMenu()
      })
    } else {
      message.error(result.message || t('Failed to create record'))
    }
  } catch (error: any) {
    message.error(error.message || t('Failed to create record'))
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.quick-create {
  width: 720px;
  background: var(--n-color);
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

.qc-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  font-weight: 500;
  font-size: 14px;
  border-bottom: 1px solid var(--n-border-color, #f0f0f0);
}

.qc-header-title {
  flex: 1;
}

/* 保存按钮 - 与详情页风格一致 */
.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: 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: 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: 1px solid #1fc76f !important;
  color: white !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;
}

.qc-menu {
  padding: 6px 0;
}

.qc-menu-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 14px;
}

.qc-menu-item:hover {
  background-color: var(--n-color-hover, #f5f5f5);
}

.qc-loading {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.qc-form {
  padding: 16px;
  max-height: 640px;
  overflow-y: auto;
}

.qc-field {
  margin-bottom: 12px;
}
</style>
