<template>
  <div class="space-y-3">
    <NSpace align="center">
      <NSelect v-model:value="target" :options="targetOptions" style="width: 240px" size="small" />
      <NCheckbox v-model:checked="staged"> 已暂存 (--cached) </NCheckbox>
      <NInput v-model:value="refModel" placeholder="ref (可选)" size="small" style="width: 140px" />
      <NInput
        v-model:value="against"
        placeholder="against (可选)"
        size="small"
        style="width: 140px"
      />
      <NButton type="primary" size="small" :loading="loading" @click="load"> 刷新差异 </NButton>
    </NSpace>

    <NSpin :show="loading">
      <DiffViewer :diff="diff" :truncated="truncated" />
    </NSpin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { NSpace, NSelect, NCheckbox, NInput, NButton, NSpin, useMessage } from 'naive-ui'
import DiffViewer from '@/components/DiffViewer.vue'
import { workspacesApi } from '@/api/workspaces'
import type { Workspace, Worktree, DiffParams } from '@/api/types'

const props = defineProps<{ ws: Workspace }>()
const msg = useMessage()

const worktrees = ref<Worktree[]>([])
const target = ref<string>('main')
const staged = ref<boolean>(false)
const refModel = ref<string>('')
const against = ref<string>('')
const diff = ref<string>('')
const truncated = ref<boolean>(false)
const loading = ref<boolean>(false)

const targetOptions = computed(() => {
  const opts = [{ label: 'Main 工作区', value: 'main' }]
  for (const wt of worktrees.value) {
    opts.push({ label: `Worktree: ${wt.branch}`, value: `wt:${wt.id}` })
  }
  return opts
})

async function load() {
  loading.value = true
  try {
    const params: DiffParams = {
      staged: staged.value,
      ref: refModel.value || undefined,
      against: against.value || undefined,
    }
    let res
    if (target.value.startsWith('wt:')) {
      res = await workspacesApi.diffOnWorktree(target.value.slice(3), params)
    } else {
      res = await workspacesApi.diff(props.ws.id, params)
    }
    diff.value = res.diff
    truncated.value = res.truncated
  } catch (e: unknown) {
    msg.error('加载差异失败：' + (e instanceof Error ? e.message : String(e)))
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    worktrees.value = await workspacesApi.listWorktrees(props.ws.id)
  } catch {
    // worktree list optional for diff
  }
  await load()
})

watch(() => props.ws.id, load)
</script>
