<script setup lang="ts">
import { ref, nextTick } from 'vue'
import type { SpecFrontmatter } from '@/api/types'
import { useClickOutside } from '@/composables/useClickOutside'
import { statusClass } from '@/utils/status'

const props = defineProps<{
  modelValue: SpecFrontmatter
  isNew?: boolean
}>()

const emit = defineEmits<{ 'update:modelValue': [value: SpecFrontmatter] }>()

function update(field: keyof SpecFrontmatter, value: unknown) {
  emit('update:modelValue', { ...props.modelValue, [field]: value })
}

// Collapsible metadata — expanded by default for new specs
const expanded = ref(!!props.isNew)

// Tag input
const tagInput = ref('')
function addTag() {
  const val = tagInput.value.trim()
  if (val && !props.modelValue.tags.includes(val)) {
    update('tags', [...props.modelValue.tags, val])
  }
  tagInput.value = ''
}
function removeTag(index: number) {
  update('tags', props.modelValue.tags.filter((_: string, i: number) => i !== index))
}
function handleTagKeydown(e: KeyboardEvent) {
  if (e.key === 'Enter' || e.key === ',') {
    e.preventDefault()
    addTag()
  }
}

// Status badge dropdown
const showStatusDropdown = ref(false)
const showReviewDropdown = ref(false)
const statusDropdownRef = ref<HTMLElement | null>(null)
const reviewDropdownRef = ref<HTMLElement | null>(null)
const statusOptions = ['draft', 'todo', 'in_progress', 'done', 'blocked', 'deprecated']
const reviewOptions = ['draft', 'in_review', 'approved']

useClickOutside(statusDropdownRef, () => { showStatusDropdown.value = false })
useClickOutside(reviewDropdownRef, () => { showReviewDropdown.value = false })

function selectStatus(s: string) {
  update('status', s)
  showStatusDropdown.value = false
}
function selectReviewStatus(r: string) {
  update('review_status', r)
  showReviewDropdown.value = false
}

function reviewClass(r: string) {
  const map: Record<string, string> = {
    draft: 'bg-gray-100 text-gray-600 dark:bg-gray-800/50 dark:text-gray-400',
    in_review: 'bg-purple-50 text-purple-700 dark:bg-purple-900/50 dark:text-purple-400',
    approved: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-400',
  }
  return map[r] || map.draft
}

// Inline edit for owner/team
const editingOwner = ref(false)
const editingTeam = ref(false)
const ownerInputRef = ref<HTMLInputElement | null>(null)
const teamInputRef = ref<HTMLInputElement | null>(null)

async function startEditOwner() {
  editingOwner.value = true
  await nextTick()
  ownerInputRef.value?.focus()
}
async function startEditTeam() {
  editingTeam.value = true
  await nextTick()
  teamInputRef.value?.focus()
}
</script>

<template>
  <div class="mb-4">
    <!-- Title: large borderless input -->
    <input
      :value="modelValue.title"
      class="w-full bg-transparent text-2xl font-display font-bold text-slate-800 dark:text-slate-100 border-0 border-b-2 border-transparent focus:border-accent-500 focus:outline-none px-0 py-1 placeholder:text-slate-300 dark:placeholder:text-slate-600 transition-colors"
      placeholder="Untitled Spec"
      @input="update('title', ($event.target as HTMLInputElement).value)"
    />

    <!-- Status badges + metadata strip -->
    <div class="mt-3 flex items-center gap-3 flex-wrap">
      <!-- Status badge -->
      <div ref="statusDropdownRef" class="relative">
        <button
          class="status-badge cursor-pointer hover:ring-2 hover:ring-accent-500/30 transition-shadow"
          :class="statusClass(modelValue.status)"
          @click="showStatusDropdown = !showStatusDropdown"
        >
          {{ modelValue.status.replace('_', ' ') }}
          <svg class="w-3 h-3 ml-1 inline" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
          </svg>
        </button>
        <div v-if="showStatusDropdown" class="absolute 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-[140px]">
          <button
            v-for="s in statusOptions"
            :key="s"
            class="w-full text-left px-3 py-1.5 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt flex items-center gap-2"
            @click="selectStatus(s)"
          >
            <span class="status-badge text-[10px]" :class="statusClass(s)">{{ s.replace('_', ' ') }}</span>
          </button>
        </div>
      </div>

      <!-- Review status badge -->
      <div ref="reviewDropdownRef" class="relative">
        <button
          class="status-badge cursor-pointer hover:ring-2 hover:ring-accent-500/30 transition-shadow"
          :class="reviewClass(modelValue.review_status || 'draft')"
          @click="showReviewDropdown = !showReviewDropdown"
        >
          {{ (modelValue.review_status || 'draft').replace('_', ' ') }}
          <svg class="w-3 h-3 ml-1 inline" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
          </svg>
        </button>
        <div v-if="showReviewDropdown" class="absolute 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-[140px]">
          <button
            v-for="r in reviewOptions"
            :key="r"
            class="w-full text-left px-3 py-1.5 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt"
            @click="selectReviewStatus(r)"
          >
            <span class="status-badge text-[10px]" :class="reviewClass(r)">{{ r.replace('_', ' ') }}</span>
          </button>
        </div>
      </div>

      <span class="text-slate-300 dark:text-slate-600">|</span>

      <!-- Owner: inline click-to-edit -->
      <span class="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-1">
        <template v-if="!editingOwner">
          <span class="cursor-pointer hover:text-slate-700 dark:hover:text-slate-300" @click="startEditOwner">
            Owner: <span class="font-medium text-slate-700 dark:text-slate-300">{{ modelValue.owner || 'unset' }}</span>
          </span>
        </template>
        <template v-else>
          Owner:
          <input
            ref="ownerInputRef"
            :value="modelValue.owner"
            class="w-24 bg-transparent border-0 border-b border-accent-500 text-xs text-slate-700 dark:text-slate-300 font-medium focus:outline-none px-0 py-0"
            @input="update('owner', ($event.target as HTMLInputElement).value)"
            @blur="editingOwner = false"
            @keydown.enter="editingOwner = false"
          />
        </template>
      </span>

      <span class="text-slate-300 dark:text-slate-600">|</span>

      <!-- Team: inline click-to-edit -->
      <span class="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-1">
        <template v-if="!editingTeam">
          <span class="cursor-pointer hover:text-slate-700 dark:hover:text-slate-300" @click="startEditTeam">
            Team: <span class="font-medium text-slate-700 dark:text-slate-300">{{ modelValue.team || 'unset' }}</span>
          </span>
        </template>
        <template v-else>
          Team:
          <input
            ref="teamInputRef"
            :value="modelValue.team"
            class="w-24 bg-transparent border-0 border-b border-accent-500 text-xs text-slate-700 dark:text-slate-300 font-medium focus:outline-none px-0 py-0"
            @input="update('team', ($event.target as HTMLInputElement).value)"
            @blur="editingTeam = false"
            @keydown.enter="editingTeam = false"
          />
        </template>
      </span>

      <!-- Expand/collapse chevron -->
      <button
        class="ml-auto text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors p-1"
        :title="expanded ? 'Collapse metadata' : 'Expand metadata'"
        @click="expanded = !expanded"
      >
        <svg
          class="w-4 h-4 transition-transform duration-200"
          :class="expanded ? 'rotate-180' : ''"
          fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
        >
          <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
        </svg>
      </button>
    </div>

    <!-- Collapsible metadata section -->
    <div
      v-if="expanded"
      class="mt-3 pt-3 border-t border-border-light/60 dark:border-slate-800 space-y-3"
    >
      <!-- Tags as chips -->
      <div>
        <label class="block text-[11px] font-medium text-slate-400 uppercase tracking-wider mb-1.5">Tags</label>
        <div class="flex items-center gap-1.5 flex-wrap">
          <span
            v-for="(tag, i) in modelValue.tags"
            :key="tag"
            class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-brand-100 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
          >
            {{ tag }}
            <button
              class="text-brand-500 hover:text-brand-700 dark:hover:text-brand-200"
              @click="removeTag(i)"
            >
              <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="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </span>
          <input
            v-model="tagInput"
            class="w-20 bg-transparent border-0 text-xs text-slate-600 dark:text-slate-400 focus:outline-none placeholder:text-slate-300 dark:placeholder:text-slate-600"
            placeholder="+ add tag"
            @keydown="handleTagKeydown"
            @blur="addTag"
          />
        </div>
      </div>
    </div>
  </div>
</template>
