<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'

export interface SaveDialogResult {
  message: string
  branchName?: string
  prTitle?: string
  prBody?: string
}

const props = defineProps<{
  mode: 'commit' | 'pr'
  filePath: string
  defaultMessage: string
}>()

const emit = defineEmits<{
  confirm: [result: SaveDialogResult]
  cancel: []
}>()

function randomHex() {
  return Math.random().toString(16).slice(2, 10)
}

const commitMessage = ref(props.defaultMessage)
const branchName = ref(`specwright/edit-${randomHex()}`)
const prTitle = ref(props.defaultMessage)
const prBody = ref('Spec update via Specwright editor.')

const titleInputRef = ref<HTMLInputElement | null>(null)
const messageInputRef = ref<HTMLInputElement | null>(null)

watch(() => props.defaultMessage, (val) => {
  commitMessage.value = val
  prTitle.value = val
})

function handleConfirm() {
  if (props.mode === 'commit') {
    emit('confirm', { message: commitMessage.value })
  } else {
    emit('confirm', {
      message: commitMessage.value,
      branchName: branchName.value,
      prTitle: prTitle.value,
      prBody: prBody.value,
    })
  }
}

function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    e.preventDefault()
    emit('cancel')
  } else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
    e.preventDefault()
    handleConfirm()
  }
}

const modifierKey = typeof navigator !== 'undefined' && navigator.platform.includes('Mac') ? '\u2318' : 'Ctrl'

onMounted(() => {
  document.addEventListener('keydown', onKeydown)
  nextTick(() => {
    if (props.mode === 'pr') {
      titleInputRef.value?.focus()
      titleInputRef.value?.select()
    } else {
      messageInputRef.value?.focus()
      messageInputRef.value?.select()
    }
  })
})
onUnmounted(() => document.removeEventListener('keydown', onKeydown))
</script>

<template>
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
    <div class="bg-surface-light dark:bg-surface-alt rounded-lg shadow-lg max-w-lg w-full mx-4 flex flex-col">
      <!-- Header -->
      <div class="p-4 border-b border-border-light dark:border-slate-700">
        <h2 class="text-lg font-semibold text-slate-800 dark:text-slate-100">
          {{ mode === 'commit' ? 'Save to branch' : 'Open Pull Request' }}
        </h2>
        <p class="text-xs text-slate-400 dark:text-slate-500 mt-1 font-mono truncate">
          {{ filePath }}
        </p>
      </div>

      <!-- Body -->
      <div class="p-4 space-y-4 max-h-[60vh] overflow-y-auto">
        <!-- PR-only fields -->
        <template v-if="mode === 'pr'">
          <div>
            <label class="block text-xs font-medium text-slate-500 dark:text-slate-400 mb-1">PR title</label>
            <input
              ref="titleInputRef"
              v-model="prTitle"
              class="w-full border border-border-light dark:border-slate-600 bg-surface-light dark:bg-surface rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-500 text-slate-800 dark:text-slate-200"
              placeholder="PR title"
            />
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-500 dark:text-slate-400 mb-1">Description</label>
            <textarea
              v-model="prBody"
              rows="3"
              class="w-full border border-border-light dark:border-slate-600 bg-surface-light dark:bg-surface rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-500 text-slate-800 dark:text-slate-200 resize-none"
              placeholder="Describe the changes..."
            ></textarea>
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-500 dark:text-slate-400 mb-1">Branch name</label>
            <input
              v-model="branchName"
              class="w-full border border-border-light dark:border-slate-600 bg-surface-light dark:bg-surface rounded-md px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-accent-500 text-slate-800 dark:text-slate-200"
              placeholder="specwright/edit-..."
            />
          </div>
        </template>

        <!-- Commit message (both modes) -->
        <div>
          <label class="block text-xs font-medium text-slate-500 dark:text-slate-400 mb-1">Commit message</label>
          <input
            ref="messageInputRef"
            v-model="commitMessage"
            class="w-full border border-border-light dark:border-slate-600 bg-surface-light dark:bg-surface rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-500 text-slate-800 dark:text-slate-200"
            placeholder="Commit message"
          />
        </div>
      </div>

      <!-- Footer -->
      <div class="p-4 border-t border-border-light dark:border-slate-700 flex items-center justify-between">
        <span class="text-[10px] text-slate-400 dark:text-slate-500">
          {{ modifierKey }}+Enter to confirm
        </span>
        <div class="flex gap-2">
          <button
            class="px-3 py-1.5 text-sm rounded-md border border-border-light dark:border-slate-600 text-slate-600 dark:text-slate-400 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated transition-colors"
            @click="emit('cancel')"
          >
            Cancel
          </button>
          <button
            v-if="mode === 'commit'"
            class="px-3 py-1.5 text-sm rounded-md bg-accent-500 text-white hover:bg-accent-600 transition-colors"
            @click="handleConfirm"
          >
            Save
          </button>
          <button
            v-else
            class="px-3 py-1.5 text-sm rounded-md border border-amber-400 bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 hover:bg-amber-100 dark:hover:bg-amber-900/30 transition-colors"
            @click="handleConfirm"
          >
            Open PR
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
