<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
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: '' as string,
  requirement_number: '' as string,
  initial_prompt: '',
})
const submitting = ref(false)
const errorMsg = ref<string | null>(null)

onMounted(async () => {
  await acpStore.listAgentKinds(false)
  if (wsStore.list.length === 0) {
    await wsStore.fetchByProject(route.params.slug as string)
  }
})

async function submit() {
  errorMsg.value = null
  submitting.value = true
  try {
    const ws = wsStore.list.find((w) => w.slug === route.params.wsSlug)
    if (!ws) {
      errorMsg.value = 'Workspace not found; please reload the page.'
      return
    }
    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) req.issue_number = Number(form.value.issue_number)
    if (form.value.requirement_number)
      req.requirement_number = 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(
      `/p/${route.params.slug}/w/${route.params.wsSlug}/acp-sessions/${sess.id}`,
    )
  } catch (e) {
    errorMsg.value = `Create failed: ${e instanceof Error ? e.message : 'unknown'}`
  } finally {
    submitting.value = false
  }
}

function cancel() {
  router.push(
    `/p/${route.params.slug}/w/${route.params.wsSlug}/acp-sessions`,
  )
}
</script>

<template>
  <div class="p-6 max-w-2xl">
    <h1 class="text-2xl font-semibold mb-4">New ACP Session</h1>

    <form class="space-y-4" @submit.prevent="submit">
      <div>
        <label class="block text-sm font-medium mb-1">Agent Kind</label>
        <select
          v-model="form.agent_kind_id"
          class="block w-full border rounded px-2 py-1 text-sm"
          required
        >
          <option value="" disabled>-- choose --</option>
          <option
            v-for="k in acpStore.enabledAgentKinds"
            :key="k.id"
            :value="k.id"
          >
            {{ k.display_name }}
          </option>
        </select>
      </div>

      <div>
        <label class="block text-sm font-medium mb-1">
          Branch <span class="text-xs text-gray-500">(optional, takes priority)</span>
        </label>
        <input
          v-model="form.branch"
          class="block w-full border rounded px-2 py-1 text-sm font-mono"
          placeholder="feat/x or main"
        />
      </div>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="block text-sm font-medium mb-1">Issue # (optional)</label>
          <input
            v-model="form.issue_number"
            type="number"
            class="block w-full border rounded px-2 py-1 text-sm"
          />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Requirement # (optional)</label>
          <input
            v-model="form.requirement_number"
            type="number"
            class="block w-full border rounded px-2 py-1 text-sm"
          />
        </div>
      </div>

      <p class="text-xs text-gray-500">
        Branch resolution: explicit &gt; issue &gt; requirement &gt; auto temp branch.
      </p>

      <div>
        <label class="block text-sm font-medium mb-1">Initial Prompt (optional)</label>
        <textarea
          v-model="form.initial_prompt"
          rows="3"
          class="block w-full border rounded px-2 py-1 text-sm"
          placeholder="Send this immediately after agent ready..."
        />
      </div>

      <p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>

      <div class="flex gap-2">
        <button
          type="submit"
          class="px-3 py-1 rounded text-sm font-medium bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-300"
          :disabled="submitting || !form.agent_kind_id"
        >
          {{ submitting ? 'Creating...' : 'Create Session' }}
        </button>
        <button
          type="button"
          class="px-3 py-1 rounded text-sm border hover:bg-gray-50"
          @click="cancel"
        >
          Cancel
        </button>
      </div>
    </form>
  </div>
</template>
