<template>
  <AppShell>
    <NSpin :show="loading">
      <div
        v-if="data"
        class="space-y-6"
      >
        <!-- Header -->
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3">
            <span class="text-gray-400 font-mono text-sm">#{{ data.requirement.number }}</span>
            <h1 class="text-2xl font-semibold">
              {{ data.requirement.title }}
            </h1>
            <NTag
              :type="data.requirement.status === 'open' ? 'success' : 'default'"
              size="small"
            >
              {{ data.requirement.status === 'open' ? '开放' : '关闭' }}
            </NTag>
          </div>
          <div class="flex items-center gap-2">
            <NButton
              v-if="data.requirement.status === 'open'"
              type="warning"
              size="small"
              :loading="toggling"
              @click="onClose"
            >
              关闭需求
            </NButton>
            <NButton
              v-else
              type="primary"
              size="small"
              :loading="toggling"
              @click="onReopen"
            >
              重新开放
            </NButton>
            <NButton
              size="small"
              @click="router.back()"
            >
              返回
            </NButton>
          </div>
        </div>

        <!-- Phase flow bar -->
        <div class="flex items-center gap-1">
          <template
            v-for="(phase, idx) in PHASES"
            :key="phase"
          >
            <NButton
              :type="phase === data.requirement.phase ? 'primary' : 'default'"
              :secondary="phase !== data.requirement.phase"
              size="small"
              :disabled="phase === data.requirement.phase"
              @click="onPhaseClick(phase)"
            >
              {{ PHASE_LABELS[phase] }}
            </NButton>
            <span
              v-if="idx < PHASES.length - 1"
              class="text-gray-300 text-xs"
            >›</span>
          </template>
        </div>

        <!-- Description -->
        <NCard title="描述">
          <p
            v-if="data.requirement.description"
            class="text-gray-700 whitespace-pre-wrap"
          >
            {{ data.requirement.description }}
          </p>
          <p
            v-else
            class="text-gray-400 text-sm"
          >
            暂无描述
          </p>
        </NCard>

        <!-- Prototypes -->
        <NCard title="原型">
          <div class="flex gap-4">
            <!-- Version list -->
            <div class="w-56 shrink-0">
              <NList
                v-if="prototypes.length > 0"
                :show-divider="false"
              >
                <NListItem
                  v-for="p in prototypes"
                  :key="p.id"
                >
                  <NThing
                    class="cursor-pointer"
                    @click="onSelectPrototype(p.version)"
                  >
                    <template #header>
                      <span
                        class="text-sm font-medium"
                        :class="selectedVersion === p.version ? 'text-blue-600' : ''"
                      >v{{ p.version }}</span>
                    </template>
                    <template #header-extra>
                      <span class="text-xs text-gray-400">
                        {{ new Date(p.created_at).toLocaleString() }}
                      </span>
                    </template>
                    <span
                      v-if="p.note"
                      class="text-xs text-gray-500"
                    >{{ p.note }}</span>
                  </NThing>
                </NListItem>
              </NList>
              <NEmpty
                v-else
                description="暂无原型版本"
                size="small"
              />
            </div>

            <!-- Selected content -->
            <div class="flex-1 min-w-0">
              <p
                v-if="selectedPrototype"
                class="text-gray-700 whitespace-pre-wrap text-sm"
              >
                {{ selectedPrototype.content }}
              </p>
              <p
                v-else
                class="text-gray-400 text-sm"
              >
                选择左侧版本以查看内容
              </p>
            </div>
          </div>

          <!-- New version form -->
          <NDivider />
          <div
            v-if="data.requirement.status === 'open'"
            class="space-y-2"
          >
            <NInput
              v-model:value="newContent"
              type="textarea"
              placeholder="原型内容"
              :autosize="{ minRows: 4, maxRows: 12 }"
            />
            <NInput
              v-model:value="newNote"
              placeholder="备注（可选）"
            />
            <NButton
              type="primary"
              size="small"
              :loading="submitting"
              :disabled="!newContent.trim()"
              @click="onSubmitPrototype"
            >
              提交新版本
            </NButton>
          </div>
          <p
            v-else
            class="text-gray-400 text-sm"
          >
            需求已关闭，无法提交新版本
          </p>
        </NCard>

        <!-- Workspace card -->
        <NCard title="工作区">
          <NSelect
            :value="data.requirement.workspace_id"
            :options="workspaceOptions"
            placeholder="未关联"
            clearable
            @update:value="onWorkspaceChange"
          />
        </NCard>

        <!-- Linked Issues -->
        <NCard title="关联 Issue">
          <NList
            v-if="data.issues.length > 0"
            :show-divider="false"
          >
            <NListItem
              v-for="issue in data.issues"
              :key="issue.id"
            >
              <NThing>
                <template #header>
                  <span class="font-mono text-xs text-gray-400 mr-2">#{{ issue.number }}</span>
                  <span class="text-sm font-medium">{{ issue.title }}</span>
                </template>
                <template #header-extra>
                  <NTag
                    :type="issue.status === 'open' ? 'success' : 'default'"
                    size="tiny"
                  >
                    {{ issue.status === 'open' ? '开放' : '关闭' }}
                  </NTag>
                </template>
              </NThing>
            </NListItem>
          </NList>
          <NEmpty
            v-else
            description="暂无关联 Issue"
          />
        </NCard>
      </div>

      <div
        v-else-if="!loading"
        class="text-gray-400 text-sm py-8 text-center"
      >
        需求不存在或无权访问。
      </div>
    </NSpin>
  </AppShell>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDialog } from 'naive-ui'
import {
  NCard,
  NButton,
  NTag,
  NSpin,
  NSelect,
  NList,
  NListItem,
  NThing,
  NEmpty,
  NInput,
  NDivider,
} from 'naive-ui'
import AppShell from '@/layouts/AppShell.vue'
import { projectsApi } from '@/api/projects'
import { useRequirementsStore } from '@/stores/requirements'
import { useWorkspacesStore } from '@/stores/workspaces'
import type { Phase, Prototype, RequirementDetail } from '@/api/projects'

const PHASES: Phase[] = ['planning', 'prototyping', 'auditing', 'implementing', 'reviewing', 'done']

const PHASE_LABELS: Record<Phase, string> = {
  planning: '规划中',
  prototyping: '原型设计',
  auditing: '审核中',
  implementing: '实施中',
  reviewing: '评审中',
  done: '已完成',
}

const route = useRoute()
const router = useRouter()
const dialog = useDialog()
const store = useRequirementsStore()
const wsStore = useWorkspacesStore()

const slug = route.params.slug as string
const number = Number(route.params.number)

const loading = ref(false)
const toggling = ref(false)
const data = ref<RequirementDetail | null>(null)

const prototypes = ref<Prototype[]>([])
const selectedVersion = ref<number | null>(null)
const newContent = ref('')
const newNote = ref('')
const submitting = ref(false)

const workspaceOptions = computed(() =>
  wsStore.list.map((w) => ({ label: `${w.name} (${w.slug})`, value: w.id })),
)

const selectedPrototype = computed(() =>
  prototypes.value.find((p) => p.version === selectedVersion.value) ?? null,
)

async function fetchData() {
  loading.value = true
  try {
    const [detail] = await Promise.all([
      projectsApi.getRequirement(slug, number),
      wsStore.fetchByProject(slug),
    ])
    data.value = detail
    await refreshPrototypes()
  } finally {
    loading.value = false
  }
}

async function refreshPrototypes() {
  prototypes.value = await store.listPrototypes(slug, number)
  // 默认选中最新版本
  if (prototypes.value.length > 0) {
    const latest = prototypes.value[prototypes.value.length - 1]
    if (selectedVersion.value === null || !selectedPrototype.value) {
      selectedVersion.value = latest.version
    }
  } else {
    selectedVersion.value = null
  }
}

function onSelectPrototype(version: number) {
  selectedVersion.value = version
}

async function onSubmitPrototype() {
  if (!newContent.value.trim()) return
  submitting.value = true
  try {
    const created = await store.createPrototype(slug, number, {
      content: newContent.value,
      note: newNote.value || undefined,
    })
    newContent.value = ''
    newNote.value = ''
    selectedVersion.value = created.version
    await refreshPrototypes()
  } finally {
    submitting.value = false
  }
}

async function onWorkspaceChange(v: string | null) {
  if (!data.value) return
  await projectsApi.updateRequirement(slug, number, { workspace_id: v })
  // Re-fetch to keep data.requirement and data.issues consistent (mirrors onPhaseClick)
  data.value = await projectsApi.getRequirement(slug, number)
}

function onPhaseClick(target: Phase) {
  if (!data.value || data.value.requirement.phase === target) return
  const targetLabel = PHASE_LABELS[target]
  dialog.warning({
    title: '切换阶段',
    content: `确认将需求移至「${targetLabel}」阶段？`,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: async () => {
      await store.changePhase(slug, number, target)
      // Refresh local data to reflect the change
      data.value = await projectsApi.getRequirement(slug, number)
    },
  })
}

async function onClose() {
  toggling.value = true
  try {
    await store.close(slug, number)
    data.value = await projectsApi.getRequirement(slug, number)
  } finally {
    toggling.value = false
  }
}

async function onReopen() {
  toggling.value = true
  try {
    await store.reopen(slug, number)
    data.value = await projectsApi.getRequirement(slug, number)
  } finally {
    toggling.value = false
  }
}

onMounted(fetchData)
</script>
