<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { usePostHog } from '@/composables/usePostHog'
import { useClickOutside } from '@/composables/useClickOutside'
import { aiEditStream } from '@/api/editor'
import type { SpecSection, AcceptanceCriterion } from '@/api/types'
import AiDiffReview from './AiDiffReview.vue'

const props = defineProps<{
  section: SpecSection
  owner: string
  repo: string
}>()

const emit = defineEmits<{
  'update-prose': [content: string]
  'update-acs': [acs: AcceptanceCriterion[]]
}>()

const auth = useAuthStore()
const { track } = usePostHog()

const aiContainerRef = ref<HTMLElement | null>(null)
const showDropdown = ref(false)
const showSuggestion = ref(false)
const loading = ref(false)
const error = ref('')
const suggestionContent = ref('')
const currentAction = ref<'improve' | 'generate_acs' | 'expand'>('improve')
const capturedOriginal = ref('')

useClickOutside(aiContainerRef, () => { showDropdown.value = false })

// Build the full section text (prose + existing ACs) for diff display
function buildSectionText(): string {
  const prose = props.section.prose_content || props.section.content
  if (props.section.acceptance_criteria.length === 0) return prose
  let text = prose.trimEnd() + '\n\n### Acceptance Criteria\n\n'
  for (const ac of props.section.acceptance_criteria) {
    text += `- [${ac.checked ? 'x' : ' '}] ${ac.text}\n`
  }
  return text
}

const diffOriginal = computed(() => capturedOriginal.value)

const diffModified = computed(() => {
  if (!suggestionContent.value) return capturedOriginal.value
  if (currentAction.value === 'generate_acs') {
    // Show full section (prose + existing ACs) with new ACs appended
    return capturedOriginal.value.trimEnd() + '\n\n' + suggestionContent.value.trim() + '\n'
  }
  // For improve/expand: show the suggestion replacing the prose
  return suggestionContent.value
})

async function runAction(action: 'improve' | 'generate_acs' | 'expand') {
  showDropdown.value = false
  currentAction.value = action
  showSuggestion.value = true
  loading.value = true
  error.value = ''
  suggestionContent.value = ''

  const content = props.section.prose_content || props.section.content

  if (action === 'generate_acs') {
    // For generate_acs, capture the full section text so diff shows ACs being appended
    capturedOriginal.value = buildSectionText()
  } else {
    // For improve/expand, capture just the prose
    capturedOriginal.value = content
  }

  await aiEditStream(
    auth.org,
    props.owner,
    props.repo,
    {
      action,
      section_title: props.section.title,
      section_content: content,
      acceptance_criteria: props.section.acceptance_criteria.map(ac => ac.text),
    },
    (chunk) => { suggestionContent.value += chunk },
    () => { loading.value = false },
    (err) => { loading.value = false; error.value = err },
  )
}

function accept() {
  if (currentAction.value === 'generate_acs') {
    // Parse "- [ ] ..." lines into ACs
    const lines = suggestionContent.value.split('\n')
    const newAcs: AcceptanceCriterion[] = []
    for (const line of lines) {
      const match = line.match(/^-\s*\[[ x]\]\s+(.+)$/i)
      if (match) {
        newAcs.push({ text: match[1].trim(), checked: false, realized_in: [] })
      }
    }
    if (newAcs.length > 0) {
      emit('update-acs', [...props.section.acceptance_criteria, ...newAcs])
    }
  } else {
    emit('update-prose', suggestionContent.value)
  }
  track('ai_edit_accepted', { action: currentAction.value, section: props.section.title })
  showSuggestion.value = false
  suggestionContent.value = ''
}

function reject() {
  track('ai_edit_rejected', { action: currentAction.value, section: props.section.title })
  showSuggestion.value = false
  suggestionContent.value = ''
  error.value = ''
}
</script>

<template>
  <div ref="aiContainerRef" class="relative">
    <!-- AI sparkle button -->
    <button
      class="p-1 text-slate-300 hover:text-accent-500 dark:text-slate-600 dark:hover:text-accent-400 transition-colors"
      title="AI assist"
      @click="showDropdown = !showDropdown"
    >
      <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456z" />
      </svg>
    </button>

    <!-- Dropdown menu -->
    <div v-if="showDropdown" class="absolute right-0 z-20 mt-1 bg-surface-light dark:bg-surface-elevated border border-border-light dark:border-slate-700 rounded-lg shadow-lg py-1 min-w-[180px]">
      <button
        class="w-full text-left px-3 py-2 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt flex items-center gap-2"
        @click="runAction('improve')"
      >
        <svg class="w-3.5 h-3.5 text-blue-500" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125" />
        </svg>
        Improve section
      </button>
      <button
        class="w-full text-left px-3 py-2 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt flex items-center gap-2"
        @click="runAction('generate_acs')"
      >
        <svg class="w-3.5 h-3.5 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        Generate ACs
      </button>
      <button
        class="w-full text-left px-3 py-2 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt flex items-center gap-2"
        @click="runAction('expand')"
      >
        <svg class="w-3.5 h-3.5 text-purple-500" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15" />
        </svg>
        Expand description
      </button>
    </div>

    <!-- AI diff review modal -->
    <AiDiffReview
      v-if="showSuggestion"
      mode="modal"
      :original="diffOriginal"
      :modified="diffModified"
      :loading="loading"
      :error="error"
      :action="currentAction"
      @accept="accept"
      @reject="reject"
    />
  </div>
</template>
