<template>
  <div class="output-panel">
    <div class="panel-header">
      <h3>输出文档</h3>
      <a-button size="small" type="primary" @click="showFormatDialog = true" :disabled="!hasReadySources">
        <PlusOutlined /> 生成
      </a-button>
    </div>

    <!-- Output list -->
    <div class="output-list" v-if="outputs.length">
      <OutputItem
        v-for="output in outputs"
        :key="output.id"
        :output="output"
        @click="handlePreview(output)"
        @delete="handleDelete(output.id)"
      />
    </div>
    <a-empty v-else description="暂无输出文档" :image-style="{ height: '60px' }" />

    <!-- Generating indicator -->
    <div v-if="isGeneratingOutput" class="generating-indicator">
      <a-spin size="small" />
      <span>正在生成文档…</span>
    </div>

    <!-- Format selection dialog -->
    <OutputFormatDialog
      :open="showFormatDialog"
      :notebook-id="notebookId"
      @close="showFormatDialog = false"
      @generate="handleGenerate"
    />

    <!-- Preview drawer -->
    <OutputPreview
      :open="!!previewOutput"
      :output="previewOutput"
      @close="previewOutput = null"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useNotebookStore } from '@/stores/notebook'
import { useSSE } from '@/composables/useSSE'
import { buildOutputUrl } from '@/api/notebook'
import type { NotebookOutput } from '@/types/notebook'
import OutputItem from './OutputItem.vue'
import OutputFormatDialog from './OutputFormatDialog.vue'
import OutputPreview from './OutputPreview.vue'

const props = defineProps<{
  notebookId: string
}>()

const store = useNotebookStore()
const outputs = computed(() => store.outputs)
const isGeneratingOutput = computed(() => store.isGeneratingOutput)
const hasReadySources = computed(() => store.selectedSources.length > 0)

const showFormatDialog = ref(false)
const previewOutput = ref<NotebookOutput | null>(null)

const { connect } = useSSE()

async function handleGenerate(params: {
  output_type: string
  title: string
  custom_instructions: string
}) {
  showFormatDialog.value = false
  store.startOutputGeneration()
  let hasError = false

  try {
    await connect({
      url: buildOutputUrl(props.notebookId),
      body: params,
      onMessage(data: any) {
        if (data.type === 'text') {
          store.appendOutputChunk(data.content || '')
        } else if (data.type === 'error') {
          hasError = true
          message.error(data.content || '生成失败')
        }
      },
      async onDone() {
        if (store.isGeneratingOutput) {
          store.finishOutputGeneration()
          await store.loadOutputs(props.notebookId)
          if (!hasError) {
            message.success('文档已生成')
          }
        }
      },
      onError() {
        hasError = true
        if (store.isGeneratingOutput) {
          store.finishOutputGeneration()
          message.error('生成失败')
        }
      },
    })
  } catch {
    hasError = true
    if (store.isGeneratingOutput) {
      store.finishOutputGeneration()
      message.error('请求失败')
    }
  }
}

async function handlePreview(output: NotebookOutput) {
  if (output.status !== 'completed') return
  try {
    const full = await store.loadOutput(props.notebookId, output.id)
    previewOutput.value = full
  } catch {
    message.error('加载失败')
  }
}

function handleDelete(outputId: string) {
  Modal.confirm({
    title: '确认删除',
    content: '确定删除此输出文档？',
    okText: '删除',
    okType: 'danger',
    async onOk() {
      await store.removeOutput(props.notebookId, outputId)
      message.success('已删除')
    },
  })
}
</script>

<style scoped lang="less">
.output-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }
}

.output-list {
  flex: 1;
  overflow-y: auto;
}

.generating-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #e6f4ff;
  border-radius: 6px;
  font-size: 13px;
  color: #1890ff;
  margin-top: 8px;
}
</style>
