<template>
  <AppShell>
    <NSpin :show="store.loading">
      <div class="space-y-4">
        <!-- Header -->
        <div class="flex items-center justify-between">
          <h1 class="text-2xl font-semibold">
            需求列表
          </h1>
          <div class="flex items-center gap-3">
            <NRadioGroup
              v-model:value="viewMode"
              size="small"
            >
              <NRadioButton value="kanban">
                看板
              </NRadioButton>
              <NRadioButton value="table">
                表格
              </NRadioButton>
            </NRadioGroup>
            <NButton
              type="primary"
              @click="showCreate = true"
            >
              新建需求
            </NButton>
          </div>
        </div>

        <!-- Kanban view -->
        <div
          v-if="viewMode === 'kanban'"
          class="flex gap-3 overflow-x-auto pb-2"
        >
          <div
            v-for="phase in PHASES"
            :key="phase"
            class="flex-shrink-0 w-60 bg-gray-50 rounded-lg p-3 space-y-2"
            @dragover.prevent
            @drop="onDrop($event, phase)"
          >
            <div class="text-sm font-medium text-gray-600 px-1">
              {{ PHASE_LABELS[phase] }}
              <span class="ml-1 text-gray-400 text-xs">({{ columnItems(phase).length }})</span>
            </div>
            <NCard
              v-for="r in columnItems(phase)"
              :key="r.id"
              size="small"
              class="cursor-grab active:cursor-grabbing"
              draggable="true"
              @dragstart="onDragStart($event, r.number)"
              @click="goDetail(r.number)"
            >
              <div class="space-y-1">
                <div class="flex items-center justify-between gap-1">
                  <span class="text-xs text-gray-400 font-mono">#{{ r.number }}</span>
                  <NTag
                    :type="r.status === 'open' ? 'success' : 'default'"
                    size="tiny"
                  >
                    {{ r.status === 'open' ? '开放' : '关闭' }}
                  </NTag>
                </div>
                <p class="text-sm font-medium leading-snug">
                  {{ r.title }}
                </p>
              </div>
            </NCard>
            <div
              v-if="columnItems(phase).length === 0"
              class="text-xs text-gray-300 text-center py-4"
            >
              拖放到此处
            </div>
          </div>
        </div>

        <!-- Table view -->
        <NDataTable
          v-if="viewMode === 'table'"
          :columns="columns"
          :data="store.items"
          :row-props="rowProps"
          :bordered="false"
          striped
        />

        <div
          v-if="!store.loading && store.items.length === 0"
          class="text-gray-400 text-sm py-8 text-center"
        >
          暂无需求，点击「新建需求」创建第一条。
        </div>
      </div>
    </NSpin>

    <!-- Create modal -->
    <NModal
      v-model:show="showCreate"
      preset="card"
      title="新建需求"
      class="w-full max-w-md"
    >
      <NForm @submit.prevent="onSubmit">
        <NFormItem label="标题">
          <NInput
            v-model:value="form.title"
            placeholder="需求标题"
          />
        </NFormItem>
        <NFormItem label="描述">
          <NInput
            v-model:value="form.description"
            type="textarea"
            :rows="4"
            placeholder="（可选）"
          />
        </NFormItem>
        <div class="flex justify-end gap-2 mt-4">
          <NButton @click="showCreate = false">
            取消
          </NButton>
          <NButton
            type="primary"
            attr-type="submit"
            :loading="creating"
          >
            创建
          </NButton>
        </div>
      </NForm>
      <p
        v-if="createError"
        class="text-red-500 text-sm mt-2"
      >
        {{ createError }}
      </p>
    </NModal>
  </AppShell>
</template>

<script setup lang="ts">
import { h, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NCard,
  NButton,
  NTag,
  NRadioGroup,
  NRadioButton,
  NDataTable,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NSpin,
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import AppShell from '@/layouts/AppShell.vue'
import { useRequirementsStore } from '@/stores/requirements'
import type { Phase, Requirement } 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 store = useRequirementsStore()

const slug = route.params.slug as string
const viewMode = ref<'kanban' | 'table'>('kanban')

// ---- Kanban ----
function columnItems(phase: Phase): Requirement[] {
  return store.items.filter((r) => r.phase === phase)
}

function onDragStart(e: DragEvent, number: number) {
  e.dataTransfer?.setData('text/plain', String(number))
}

async function onDrop(e: DragEvent, target: Phase) {
  const raw = e.dataTransfer?.getData('text/plain')
  if (!raw) return
  const number = parseInt(raw, 10)
  if (isNaN(number)) return
  const item = store.items.find((r) => r.number === number)
  if (!item || item.phase === target) return
  await store.changePhase(slug, number, target)
}

// ---- Table ----
const columns: DataTableColumns<Requirement> = [
  {
    title: '#',
    key: 'number',
    width: 60,
    render: (row) => h('span', { class: 'font-mono text-xs text-gray-400' }, `#${row.number}`),
  },
  {
    title: '标题',
    key: 'title',
  },
  {
    title: '阶段',
    key: 'phase',
    width: 100,
    render: (row) =>
      h(NTag, { size: 'small' }, { default: () => PHASE_LABELS[row.phase] }),
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    render: (row) =>
      h(
        NTag,
        { size: 'small', type: row.status === 'open' ? 'success' : 'default' },
        { default: () => (row.status === 'open' ? '开放' : '关闭') },
      ),
  },
]

function rowProps(row: Requirement) {
  return {
    style: 'cursor: pointer',
    onClick: () => goDetail(row.number),
  }
}

function goDetail(number: number) {
  router.push({ name: 'requirement-detail', params: { slug, number } })
}

// ---- Create modal ----
const showCreate = ref(false)
const creating = ref(false)
const createError = ref('')
const form = ref({ title: '', description: '' })

async function onSubmit() {
  createError.value = ''
  if (!form.value.title.trim()) {
    createError.value = '标题不能为空'
    return
  }
  creating.value = true
  try {
    const r = await store.create(slug, {
      title: form.value.title,
      description: form.value.description || undefined,
    })
    showCreate.value = false
    form.value = { title: '', description: '' }
    goDetail(r.number)
  } catch (e) {
    createError.value = e instanceof Error ? e.message : '创建失败'
  } finally {
    creating.value = false
  }
}

onMounted(() => store.refresh(slug))
</script>
