<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSelect,
  NSpin,
} from 'naive-ui'

import AppShell from '@/layouts/AppShell.vue'
import { useAcpStore } from '@/stores/acp'
import { useWorkspacesStore } from '@/stores/workspaces'

const route = useRoute()
const router = useRouter()
const acpStore = useAcpStore()
const wsStore = useWorkspacesStore()

const form = ref({
  agent_kind_id: '',
  branch: '',
  issue_number: null as number | null,
  requirement_number: null as number | null,
  initial_prompt: '',
})
const submitting = ref(false)
const errorMsg = ref<string | null>(null)

const projectSlug = computed(() => route.params.slug as string)
const workspaceSlug = computed(() => route.params.wsSlug as string)

const agentKindOptions = computed(() =>
  acpStore.enabledAgentKinds.map((k) => ({
    label: k.display_name,
    value: k.id,
  })),
)

const exclusiveCount = computed(
  () =>
    [form.value.branch, form.value.issue_number, form.value.requirement_number].filter(Boolean)
      .length,
)

const canSubmit = computed(
  () => !!form.value.agent_kind_id && exclusiveCount.value <= 1 && !submitting.value,
)

onMounted(async () => {
  if (typeof route.query.requirement_number === 'string') {
    form.value.requirement_number = Number(route.query.requirement_number)
  }
  if (typeof route.query.issue_number === 'string') {
    form.value.issue_number = Number(route.query.issue_number)
  }
  await acpStore.listAgentKinds(false)
  if (wsStore.list.length === 0) {
    await wsStore.fetchByProject(projectSlug.value)
  }
})

async function submit() {
  errorMsg.value = null

  if (exclusiveCount.value > 1) {
    errorMsg.value = 'Branch、Issue # 和 Requirement # 最多只能填写一项'
    return
  }

  const ws = wsStore.list.find((w) => w.slug === workspaceSlug.value)
  if (!ws) {
    errorMsg.value = '未找到工作区，请刷新页面后重试'
    return
  }

  submitting.value = true
  try {
    const req: {
      workspace_id: string
      agent_kind_id: string
      branch?: string
      issue_number?: number
      requirement_number?: number
      initial_prompt?: string
    } = {
      workspace_id: ws.id,
      agent_kind_id: form.value.agent_kind_id,
    }
    if (form.value.branch) req.branch = form.value.branch
    if (form.value.issue_number != null) req.issue_number = form.value.issue_number
    if (form.value.requirement_number != null) req.requirement_number = form.value.requirement_number
    if (form.value.initial_prompt) req.initial_prompt = form.value.initial_prompt

    const sess = await acpStore.createSession(req)
    router.push({
      name: 'acp-sessions-detail',
      params: {
        slug: projectSlug.value,
        wsSlug: workspaceSlug.value,
        sessionId: sess.id,
      },
    })
  } catch (e) {
    errorMsg.value = `创建失败：${e instanceof Error ? e.message : 'unknown'}`
  } finally {
    submitting.value = false
  }
}

function cancel() {
  router.push({
    name: 'acp-sessions-list',
    params: { slug: projectSlug.value, wsSlug: workspaceSlug.value },
  })
}
</script>

<template>
  <AppShell>
    <NSpin :show="acpStore.loading || wsStore.loading">
      <div class="p-6 max-w-2xl">
        <h1 class="text-2xl font-semibold mb-4">
          新建 ACP 会话
        </h1>

        <NForm @submit.prevent="submit">
          <NFormItem
            label="Agent Kind"
            required
          >
            <NSelect
              v-model:value="form.agent_kind_id"
              :options="agentKindOptions"
              placeholder="请选择 Agent Kind"
            />
          </NFormItem>

          <NFormItem label="Branch">
            <NInput
              v-model:value="form.branch"
              placeholder="feat/x 或 main"
            />
          </NFormItem>

          <div class="grid grid-cols-2 gap-4">
            <NFormItem label="Issue #">
              <NInputNumber
                v-model:value="form.issue_number"
                :min="1"
                placeholder="可选"
                data-testid="issue-number-input"
              />
            </NFormItem>
            <NFormItem label="Requirement #">
              <NInputNumber
                v-model:value="form.requirement_number"
                :min="1"
                placeholder="可选"
                data-testid="requirement-number-input"
              />
            </NFormItem>
          </div>

          <p class="text-xs text-gray-500 mb-4">
            Branch、Issue #、Requirement # 最多填写一项；全部留空将使用自动临时分支。
          </p>

          <NFormItem label="Initial Prompt">
            <NInput
              v-model:value="form.initial_prompt"
              type="textarea"
              :rows="3"
              placeholder="会话启动后立即发送给 Agent 的提示词（可选）"
            />
          </NFormItem>

          <div class="flex justify-end gap-2">
            <NButton @click="cancel">
              取消
            </NButton>
            <NButton
              type="primary"
              attr-type="submit"
              :loading="submitting"
              :disabled="!canSubmit"
              data-testid="submit-btn"
            >
              创建会话
            </NButton>
          </div>
        </NForm>

        <p
          v-if="errorMsg"
          class="text-red-500 text-sm mt-2"
        >
          {{ errorMsg }}
        </p>
      </div>
    </NSpin>
  </AppShell>
</template>
