<template>
  <div class="onboarding-block" :class="{ 'edit-mode': editMode }">
    <div v-if="!isDismissed" class="onboarding-widget">
      <div class="onboarding-header">
        <div class="onboarding-title-section">
          <h3 class="onboarding-title">{{ title }}</h3>
          <p v-if="subtitle" class="onboarding-subtitle">{{ subtitle }}</p>
        </div>
        <div v-if="!editMode" class="onboarding-actions">
          <n-button text @click="handleDismiss">
            <template #icon>
              <Icon icon="tabler:x" />
            </template>
            {{ t('Dismiss') }}
          </n-button>
        </div>
      </div>
      
      <div v-if="!showSuccess" class="onboarding-content">
        <div class="onboarding-steps">
          <div 
            v-for="(step, index) in steps" 
            :key="step.name"
            class="onboarding-step"
            :class="{ 
              'active': activeStepIndex === index,
              'complete': step.is_complete,
              'skipped': step.is_skipped
            }"
            @click="setActiveStep(index)"
          >
            <div class="step-indicator">
              <Icon 
                v-if="step.is_complete" 
                icon="tabler:circle-check-filled" 
                :style="{ color: '#18a058', fontSize: '20px' }"
              />
              <Icon 
                v-else-if="step.is_skipped" 
                icon="tabler:circle-x" 
                :style="{ color: '#94a3b8', fontSize: '20px' }"
              />
              <Icon 
                v-else
                icon="tabler:circle" 
                :style="{ color: '#d1d5db', fontSize: '20px' }"
              />
            </div>
            <span class="step-title">{{ t(step.title) }}</span>
            <n-button 
              v-if="!step.is_complete && !step.is_skipped && !editMode" 
              text 
              size="tiny" 
              class="step-skip-btn"
              @click.stop="skipStep(step)"
            >
              {{ t('Skip') }}
            </n-button>
          </div>
        </div>
        
        <div v-if="activeStep" class="step-preview">
          <div class="step-body">
            <div v-html="stepDescription"></div>
          </div>
          <div class="step-footer">
            <n-button v-if="!editMode" type="primary" @click="handleStepAction">
              {{ stepActionLabel }}
            </n-button>
          </div>
        </div>
      </div>
      
      <div v-else class="onboarding-success">
        <div class="success-content">
          <Icon icon="tabler:confetti" :style="{ fontSize: '64px', color: '#18a058' }" />
          <h3>{{ success }}</h3>
          <div v-if="pagesUrl" class="success-pgs">
            <a :href="pagesUrl" target="_blank">{{ t('View Documentation') }}</a>
          </div>
          <n-button type="primary" @click="$emit('delete')">
            {{ t('Continue') }}
          </n-button>
        </div>
      </div>
    </div>
    <div v-if="editMode" class="card-actions">
      <button class="action-btn" @click="$emit('edit')" :title="t('Edit')">
        <Icon icon="tabler:edit" />
      </button>
      <button class="action-btn drag-handle" :title="t('Drag')">
        <Icon icon="tabler:grip-vertical" />
      </button>
      <n-dropdown trigger="click" :options="menuOptions" @select="handleMenuSelect">
        <button class="action-btn" :title="t('More')">
          <Icon icon="tabler:dots" />
        </button>
      </n-dropdown>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, h } from 'vue'
import { Icon } from '@iconify/vue'
import { NButton, NDropdown, useMessage } from 'naive-ui'
import { t } from '@/shared/i18n'
import { api } from '@/shared/api/common'

const props = defineProps<{
  onboardingName: string
  onboardingData?: any
  editMode: boolean
}>()

const emit = defineEmits<{
  edit: []
  delete: []
}>()

const menuOptions = computed(() => [
  { label: t('Delete'), key: 'delete', icon: () => h(Icon, { icon: 'tabler:trash', size: 16 }) }
])

function handleMenuSelect(key: string) {
  if (key === 'delete') {
    emit('delete')
  }
}

const message = useMessage()
const loading = ref(false)
const title = ref('')
const subtitle = ref('')
const success = ref('')
const pagesUrl = ref('')
const steps = ref<any[]>([])
const activeStepIndex = ref(0)
const isDismissed = ref(false)
const showSuccess = ref(false)

const activeStep = computed(() => steps.value[activeStepIndex.value])

const stepDescription = computed(() => {
  if (!activeStep.value) return ''
  const desc = activeStep.value.description || activeStep.value.title
  // Simple markdown-like conversion for basic formatting
  return t(desc)
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2" target="_blank">$1</a>')
    .replace(/\n/g, '<br>')
})

const stepActionLabel = computed(() => {
  if (!activeStep.value) return t('Continue')
  return t(activeStep.value.action_label || activeStep.value.action || 'Continue')
})

watch(() => props.onboardingData, (newData) => {
  if (newData) {
    loadOnboardingFromData(newData)
  }
}, { immediate: true })

onMounted(() => {
  checkDismissed()
  if (!props.onboardingData) {
    loadOnboarding()
  }
})

function checkDismissed() {
  if (props.editMode) return
  try {
    const dismissed = JSON.parse(localStorage.getItem('dismissed-onboarding') || '{}')
    if (dismissed[title.value]) {
      const lastDismissed = new Date(dismissed[title.value])
      const now = new Date()
      const hoursDiff = (now.getTime() - lastDismissed.getTime()) / (1000 * 60 * 60)
      if (hoursDiff < 24) {
        isDismissed.value = true
      }
    }
  } catch (e) {
    console.error('Error checking dismissed state:', e)
  }
}

function loadOnboardingFromData(data: any) {
  title.value = t(data.title || props.onboardingName)
  subtitle.value = data.subtitle ? t(data.subtitle) : ''
  success.value = data.success ? t(data.success) : t('You seem good to go!')
  pagesUrl.value = data.pgs_url || ''
  steps.value = data.items || []
  
  const firstIncomplete = steps.value.findIndex(s => !s.is_complete && !s.is_skipped)
  activeStepIndex.value = firstIncomplete >= 0 ? firstIncomplete : 0
  
  checkIfComplete()
}

async function loadOnboarding() {
  if (loading.value) return
  loading.value = true
  
  try {
    const pg = await api.call('jingrow.client.get_value', {
      pagetype: 'Module Onboarding',
      filters: { name: props.onboardingName },
      fieldname: ['title', 'subtitle', 'success_message', 'documentation_url', 'steps']
    })
    
    if (!pg?.message) return
    
    const onboardingDoc = pg.message
    title.value = t(onboardingDoc.title || props.onboardingName)
    subtitle.value = onboardingDoc.subtitle ? t(onboardingDoc.subtitle) : ''
    success.value = onboardingDoc.success_message ? t(onboardingDoc.success_message) : t('You seem good to go!')
    pagesUrl.value = onboardingDoc.documentation_url || ''
    
    if (onboardingDoc.steps) {
      const stepsRes = await api.call('jingrow.desk.pagetype.onboarding_step.onboarding_step.get_onboarding_steps', {
        ob_steps: JSON.stringify(onboardingDoc.steps)
      })
      steps.value = stepsRes?.message || []
      
      const firstIncomplete = steps.value.findIndex(s => !s.is_complete && !s.is_skipped)
      activeStepIndex.value = firstIncomplete >= 0 ? firstIncomplete : 0
      
      checkIfComplete()
    }
  } catch (error: any) {
    console.error('Failed to load onboarding:', error)
  } finally {
    loading.value = false
  }
}

function setActiveStep(index: number) {
  activeStepIndex.value = index
}

function handleDismiss() {
  try {
    const dismissed = JSON.parse(localStorage.getItem('dismissed-onboarding') || '{}')
    dismissed[title.value] = new Date().toISOString()
    localStorage.setItem('dismissed-onboarding', JSON.stringify(dismissed))
    isDismissed.value = true
  } catch (e) {
    console.error('Error dismissing onboarding:', e)
  }
}

async function handleStepAction() {
  if (!activeStep.value || props.editMode) return
  
  const step = activeStep.value
  
  switch (step.action) {
    case 'Create Entry':
      window.location.hash = `/app/${step.reference_document}/new`
      await markComplete(step)
      break
    case 'Go to Page':
      window.location.hash = step.path
      await markComplete(step)
      break
    default:
      await markComplete(step)
  }
}

async function markComplete(step: any) {
  try {
    await api.call('jingrow.desk.desktop.update_onboarding_step', {
      name: step.name,
      field: 'is_complete',
      value: 1
    })
    
    step.is_complete = true
    step.is_skipped = false
    activateNextStep()
    checkIfComplete()
  } catch (error: any) {
    console.error('Failed to mark step complete:', error)
    message.error(t('Failed to update step'))
  }
}

async function skipStep(step: any) {
  try {
    await api.call('jingrow.desk.desktop.update_onboarding_step', {
      name: step.name,
      field: 'is_skipped',
      value: 1
    })
    
    step.is_skipped = true
    step.is_complete = false
    activateNextStep()
    checkIfComplete()
  } catch (error: any) {
    console.error('Failed to skip step:', error)
    message.error(t('Failed to update step'))
  }
}

function activateNextStep() {
  const nextIncomplete = steps.value.findIndex(
    (s, i) => i > activeStepIndex.value && !s.is_complete && !s.is_skipped
  )
  if (nextIncomplete >= 0) {
    activeStepIndex.value = nextIncomplete
  }
}

function checkIfComplete() {
  const allDone = steps.value.every(s => s.is_complete || s.is_skipped)
  if (allDone && steps.value.length > 0) {
    showSuccess.value = true
  }
}
</script>

<style scoped>
.onboarding-block {
  background: #fff;
  border: 1px solid #eef2f7;
  border-radius: 12px;
  padding: 16px;
  position: relative;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(15,23,42,0.04);
}

.edit-mode .onboarding-block {
  border: 2px dashed transparent;
}

.onboarding-widget {
  width: 100%;
  padding: 20px;
}

.onboarding-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.onboarding-title-section {
  flex: 1;
}

.onboarding-title {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: #0f172a;
}

.onboarding-subtitle {
  margin: 0;
  font-size: 14px;
  color: #64748b;
}

.onboarding-actions {
  margin-left: 16px;
}

.onboarding-content {
  display: flex;
  gap: 24px;
}

.onboarding-steps {
  min-width: 280px;
  max-width: 320px;
}

.onboarding-step {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.onboarding-step:hover {
  background-color: #f9fafb;
}

.onboarding-step.active {
  background-color: #eff6ff;
  border: 1px solid #3b82f6;
}

.onboarding-step.complete {
  opacity: 0.7;
}

.onboarding-step.skipped {
  opacity: 0.5;
}

.onboarding-step.skipped .step-title {
  text-decoration: line-through;
}

.step-indicator {
  flex-shrink: 0;
}

.step-title {
  flex: 1;
  font-size: 14px;
  color: #374151;
}

.step-skip-btn {
  opacity: 0;
  transition: opacity 0.2s;
}

.onboarding-step:hover .step-skip-btn {
  opacity: 1;
}

.step-preview {
  flex: 1;
  padding: 20px;
  background: #f9fafb;
  border-radius: 8px;
}

.step-body {
  margin-bottom: 20px;
  color: #374151;
  line-height: 1.6;
}

.step-body :deep(h1),
.step-body :deep(h2) {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #0f172a;
}

.step-body :deep(p) {
  margin: 0 0 12px 0;
}

.step-body :deep(a) {
  color: #3b82f6;
  text-decoration: none;
}

.step-body :deep(a:hover) {
  text-decoration: underline;
}

.step-footer {
  display: flex;
  gap: 8px;
}

.onboarding-success {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.success-content {
  text-align: center;
  max-width: 400px;
}

.success-content h3 {
  margin: 16px 0;
  font-size: 20px;
  font-weight: 600;
  color: #0f172a;
}

.success-pgs {
  margin: 16px 0;
}

.success-pgs a {
  color: #3b82f6;
  text-decoration: none;
}

.success-pgs a:hover {
  text-decoration: underline;
}

.card-actions {
  display: flex;
  gap: 4px;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
  position: absolute;
  top: 8px;
  right: 8px;
}

.edit-mode:hover .card-actions {
  opacity: 1;
}

.action-btn {
  background: transparent;
  border: none;
  color: #64748b;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s;
  font-size: 16px;
}

.action-btn:hover {
  background: #f1f5f9;
  color: #0f172a;
}

.drag-handle {
  cursor: grab;
}

.drag-handle:active {
  cursor: grabbing;
}
</style>
