<script lang="ts" setup>
import { toast } from 'vue-sonner'
import { generateLessonPlan, type AIGeneratedContentResponse } from '~/api/aifn'
import type { AIGeneratedContent } from '~/components/ai'
import type { FetchError } from '~/types'

const tab = ref('text')
const loading = ref(false)

const input = ref('')

const data = ref<AIGeneratedContent | null>(null)

const onGenerateClick = () => {
  if (input.value) {
    loading.value = true
    toast.promise(
      generateLessonPlan({
        query: input.value,
      }),
      {
        loading: '生成中...',
        success: (res: AIGeneratedContentResponse) => {
          data.value = res.data
          return '生成成功'
        },
        error: (err: FetchError) => {
          data.value = null
          return err.message
        },
        finally: () => {
          loading.value = false
        },
      },
    )
  } else {
    data.value = null
  }
}
</script>

<template>
  <div class="flex flex-col gap-4">
    <Tabs
      v-model="tab"
      class="w-[400px]"
    >
      <TabsList>
        <TabsTrigger value="text">
          <div class="flex items-center gap-1">
            <Icon name="tabler:article" />
            <span>文本生成</span>
          </div>
        </TabsTrigger>
        <TabsTrigger value="chapter">
          <div class="flex items-center gap-1">
            <Icon name="tabler:text-plus" />
            <span>章节生成</span>
          </div>
        </TabsTrigger>
        <TabsTrigger
          value="bot"
          disabled
        >
          <div class="flex items-center gap-1">
            <Icon name="tabler:robot" />
            <span>课程智能体</span>
          </div>
        </TabsTrigger>
      </TabsList>
    </Tabs>
    <div class="flex items-start gap-4">
      <div
        v-if="tab === 'chapter'"
        class="flex h-20 flex-col justify-center items-center gap-1 px-8 rounded-md border"
      >
        <Icon
          name="tabler:text-plus"
          class="text-3xl"
        />
        <span class="text-xs font-medium">选择章节</span>
      </div>
      <Textarea
        v-model="input"
        placeholder="请输入文本来生成内容"
        class="h-20 flex-1"
      />
      <div class="flex flex-col items-center gap-2">
        <Button
          size="lg"
          :disabled="loading"
          @click="onGenerateClick"
        >
          <Icon
            v-if="loading"
            name="svg-spinners:180-ring-with-bg"
          />
          <Icon
            v-else
            name="mage:stars-c-fill"
          />
          生成教案
        </Button>
        <p class="text-xs text-foreground/40">内容由 AI 生成，仅供参考</p>
      </div>
    </div>
    <AiGeneratedContent :data />
  </div>
</template>

<style scoped></style>
