<template>
  <NSpace
    vertical
    size="large"
  >
    <NCard title="基本信息">
      <NForm
        label-placement="left"
        :label-width="100"
      >
        <NFormItem label="名称">
          <NInput v-model:value="form.name" />
        </NFormItem>
        <NFormItem label="描述">
          <NInput
            v-model:value="form.description"
            type="textarea"
          />
        </NFormItem>
        <NFormItem label="默认分支">
          <NInput v-model:value="form.default_branch" />
        </NFormItem>
      </NForm>
      <NButton
        type="primary"
        :loading="savingCore"
        @click="saveCore"
      >
        保存
      </NButton>
    </NCard>

    <NCard title="Git 凭据">
      <p class="text-sm text-gray-500 mb-2">
        当前指纹：{{ store.credential?.fingerprint || '（未设置）' }}
      </p>
      <NForm
        label-placement="left"
        :label-width="100"
      >
        <NFormItem label="类型">
          <NSelect
            v-model:value="credForm.kind"
            :options="kindOptions"
          />
        </NFormItem>
        <NFormItem
          v-if="credForm.kind === 'pat'"
          label="用户名"
        >
          <NInput v-model:value="credForm.username" />
        </NFormItem>
        <NFormItem
          v-if="credForm.kind === 'pat'"
          label="Token"
        >
          <NInput
            v-model:value="credForm.secret"
            type="password"
            show-password-on="click"
          />
        </NFormItem>
        <NFormItem
          v-if="credForm.kind === 'ssh_key'"
          label="私钥（PEM）"
        >
          <NInput
            v-model:value="credForm.secret"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
          />
        </NFormItem>
      </NForm>
      <NButton
        type="primary"
        :loading="savingCred"
        @click="saveCred"
      >
        替换凭据
      </NButton>
    </NCard>

    <NCard title="危险区">
      <NButton
        type="error"
        @click="onDelete"
      >
        删除工作区
      </NButton>
    </NCard>
  </NSpace>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import {
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NButton,
  NSpace,
  NCard,
  useMessage,
  useDialog,
} from 'naive-ui'
import { useRouter } from 'vue-router'
import { useWorkspacesStore } from '@/stores/workspaces'
import type { CredentialKind, CredentialUpsertBody, Workspace } from '@/api/types'

interface CoreFormState {
  name: string
  description: string
  default_branch: string
}

interface CredFormState {
  kind: CredentialKind
  username: string
  secret: string
}

const props = defineProps<{ ws: Workspace }>()
const store = useWorkspacesStore()
const msg = useMessage()
const dialog = useDialog()
const router = useRouter()

const form = ref<CoreFormState>({
  name: props.ws.name,
  description: props.ws.description,
  default_branch: props.ws.default_branch,
})

const credForm = ref<CredFormState>({
  kind: store.credential?.kind ?? 'none',
  username: store.credential?.username ?? '',
  secret: '',
})

const savingCore = ref(false)
const savingCred = ref(false)

const kindOptions: { label: string; value: CredentialKind }[] = [
  { label: 'HTTPS PAT', value: 'pat' },
  { label: 'SSH Key', value: 'ssh_key' },
  { label: '公开仓库（无凭据）', value: 'none' },
]

async function saveCore() {
  savingCore.value = true
  try {
    await store.update(props.ws.id, form.value)
    msg.success('已保存')
  } catch (e: unknown) {
    msg.error('保存失败：' + (e instanceof Error ? e.message : String(e)))
  } finally {
    savingCore.value = false
  }
}

async function saveCred() {
  // kind!=='none' 时 secret 必填，避免向后端推空 token；与 WorkspaceCreateModal 校验一致。
  if (credForm.value.kind !== 'none' && !credForm.value.secret) {
    msg.error('请填写凭据 secret')
    return
  }
  // kind==='none' 时不带 username/secret，避免之前残留的 PAT 用户名混入 'none' 请求体。
  const body: CredentialUpsertBody =
    credForm.value.kind === 'none'
      ? { kind: 'none' }
      : {
          kind: credForm.value.kind,
          username: credForm.value.username,
          secret: credForm.value.secret,
        }
  savingCred.value = true
  try {
    await store.upsertCredential(props.ws.id, body)
    credForm.value.secret = ''
    msg.success('凭据已替换')
  } catch (e: unknown) {
    msg.error('替换失败：' + (e instanceof Error ? e.message : String(e)))
  } finally {
    savingCred.value = false
  }
}

function onDelete() {
  dialog.error({
    title: '确认删除工作区',
    content: '将级联删除所有 worktree 并 rm -rf 磁盘文件，不可恢复。',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await store.remove(props.ws.id)
        msg.success('已删除')
        router.push(`/p/${router.currentRoute.value.params.slug}/workspaces`)
      } catch (e: unknown) {
        msg.error('删除失败：' + (e instanceof Error ? e.message : String(e)))
      }
    },
  })
}
</script>
