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

const props = defineProps<{
  editorRef: InstanceType<typeof MonacoEditor> | null
  content: string
  owner: string
  repo: string
}>()

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

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

const showPanel = ref(false)
const loading = ref(false)
const error = ref('')
const suggestionContent = ref('')
const currentAction = ref<'improve' | 'generate_acs' | 'expand'>('improve')
const hadSelection = ref(false)
const capturedOriginal = ref('')

function getSelectedText(): { text: string; hasSelection: boolean } {
  const editor = (props.editorRef as unknown as { editor: { value: unknown } })?.editor?.value as {
    getSelection: () => { isEmpty: () => boolean }
    getModel: () => { getValueInRange: (range: unknown) => string; getValue: () => string }
  } | null

  if (!editor) return { text: props.content, hasSelection: false }

  const selection = editor.getSelection()
  if (selection && !selection.isEmpty()) {
    const model = editor.getModel()
    if (model) {
      return { text: model.getValueInRange(selection), hasSelection: true }
    }
  }
  return { text: props.content, hasSelection: false }
}

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

  const { text, hasSelection } = getSelectedText()
  hadSelection.value = hasSelection
  capturedOriginal.value = text

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

function accept() {
  const editor = (props.editorRef as unknown as { editor: { value: unknown } })?.editor?.value as {
    getSelection: () => { isEmpty: () => boolean }
    executeEdits: (source: string, edits: unknown[]) => void
  } | null

  if (editor && hadSelection.value) {
    const selection = editor.getSelection()
    if (selection && !selection.isEmpty()) {
      // Replace selection with AI output
      editor.executeEdits('ai-edit', [{
        range: selection,
        text: suggestionContent.value,
      }])
    } else {
      // Selection was cleared during streaming — replace full content
      emit('update-content', suggestionContent.value)
    }
  } else if (currentAction.value === 'generate_acs') {
    // For generate_acs without selection, append the new ACs at the end
    emit('update-content', props.content.trimEnd() + '\n\n' + suggestionContent.value.trim() + '\n')
  } else {
    // For improve/expand without selection, replace full content
    emit('update-content', suggestionContent.value)
  }

  track('ai_edit_accepted', { action: currentAction.value, mode: 'source' })
  showPanel.value = false
  suggestionContent.value = ''
}

function reject() {
  track('ai_edit_rejected', { action: currentAction.value, mode: 'source' })
  showPanel.value = false
  suggestionContent.value = ''
  error.value = ''
}

const hasContent = computed(() => props.content.trim().length > 0)

defineExpose({
  showPanel,
  loading,
  error,
  suggestionContent,
  currentAction,
  capturedOriginal,
  hadSelection,
  accept,
  reject,
})
</script>

<template>
  <div v-if="hasContent">
    <!-- AI action buttons -->
    <div v-if="!showPanel" class="flex items-center gap-2">
      <span class="text-[11px] text-slate-400 dark:text-slate-500 flex items-center gap-1">
        <svg class="w-3 h-3" 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>
        AI Assist
      </span>
      <button
        class="px-2 py-0.5 text-[11px] rounded border border-border-light dark:border-slate-700 text-slate-500 dark:text-slate-400 hover:border-accent-400 hover:text-accent-500 transition-colors"
        @click="runAction('improve')"
      >
        Improve
      </button>
      <button
        class="px-2 py-0.5 text-[11px] rounded border border-border-light dark:border-slate-700 text-slate-500 dark:text-slate-400 hover:border-accent-400 hover:text-accent-500 transition-colors"
        @click="runAction('generate_acs')"
      >
        Generate ACs
      </button>
      <button
        class="px-2 py-0.5 text-[11px] rounded border border-border-light dark:border-slate-700 text-slate-500 dark:text-slate-400 hover:border-accent-400 hover:text-accent-500 transition-colors"
        @click="runAction('expand')"
      >
        Expand
      </button>
      <span class="text-[10px] text-slate-300 dark:text-slate-600">Select a section to target it, or run on the full document</span>
    </div>
  </div>
</template>
