<script setup lang="ts">
import { Eye, Loader2, Megaphone, Send } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

interface Application {
  id: number
  name: string
}

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const saving = ref(false)
const applications = ref<Application[]>([])

const formData = ref({
  application_id: '',
  title: '',
  content: '',
  type: 'info' as 'info' | 'warning' | 'error' | 'success',
  status: 'active' as 'active' | 'inactive',
  is_top: false,
})

const typeOptions = [
  { value: 'info', label: '信息', color: 'bg-blue-500', desc: '普通通知信息' },
  { value: 'warning', label: '警告', color: 'bg-yellow-500', desc: '需要注意的内容' },
  { value: 'error', label: '错误', color: 'bg-red-500', desc: '错误或故障通知' },
  { value: 'success', label: '成功', color: 'bg-green-500', desc: '成功状态通知' },
]

const selectedApplication = computed(() => {
  return applications.value.find(app => String(app.id) === formData.value.application_id)
})

const selectedType = computed(() => {
  return typeOptions.find(t => t.value === formData.value.type)
})

async function fetchApplications() {
  loading.value = true
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
    const appParam = route.query.app as string
    if (appParam) {
      formData.value.application_id = appParam
    }
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
  finally {
    loading.value = false
  }
}

async function handleSubmit() {
  if (!formData.value.application_id) {
    toast.error('请选择应用')
    return
  }
  if (!formData.value.title) {
    toast.error('请输入公告标题')
    return
  }
  if (!formData.value.content) {
    toast.error('请输入公告内容')
    return
  }

  saving.value = true
  try {
    await api.post(`/dev/applications/${formData.value.application_id}/announcements`, {
      title: formData.value.title,
      content: formData.value.content,
      type: formData.value.type,
      status: formData.value.status,
      is_top: formData.value.is_top,
    })
    toast.success('公告创建成功')
    router.push('/admin/announcements')
  }
  catch (error: any) {
    console.error('创建公告失败:', error)
    toast.error(error.message || '创建失败')
  }
  finally {
    saving.value = false
  }
}

onMounted(() => {
  fetchApplications()
})
</script>

<template>
  <BasicPage
    title="创建公告"
    description="创建新的系统公告"
    :breadcrumbs="[
      { title: '公告管理', href: '/admin/announcements' },
      { title: '创建公告' },
    ]"
    sticky
  >
    <div class="space-y-6">
      <div class="grid gap-6 lg:grid-cols-3">
        <div class="lg:col-span-2 space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Megaphone class="size-5" />
                公告配置
              </UiCardTitle>
              <UiCardDescription>填写公告的基本信息和内容</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel>选择应用 <span class="text-destructive">*</span></UiLabel>
                <UiSelect v-model="formData.application_id" :disabled="saving || loading">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="选择应用" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem
                      v-for="app in applications"
                      :key="app.id"
                      :value="String(app.id)"
                    >
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="title">
                  公告标题 <span class="text-destructive">*</span>
                </UiLabel>
                <UiInput
                  id="title"
                  v-model="formData.title"
                  placeholder="输入公告标题"
                  :disabled="saving"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="content">
                  公告内容 <span class="text-destructive">*</span>
                </UiLabel>
                <textarea
                  id="content"
                  v-model="formData.content"
                  class="flex min-h-[180px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                  placeholder="输入公告详细内容..."
                  :disabled="saving"
                />
              </div>

              <div class="space-y-2">
                <UiLabel>公告类型</UiLabel>
                <UiSelect v-model="formData.type" :disabled="saving">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="选择类型" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="type in typeOptions" :key="type.value" :value="type.value">
                      <div class="flex items-center gap-2">
                        <span class="w-2 h-2 rounded-full" :class="type.color" />
                        {{ type.label }}
                      </div>
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="flex items-center justify-between rounded-lg border p-4">
                <div class="space-y-0.5">
                  <UiLabel class="text-base">
                    发布状态
                  </UiLabel>
                  <p class="text-sm text-muted-foreground">
                    启用后公告将对用户可见
                  </p>
                </div>
                <UiSwitch
                  :checked="formData.status === 'active'"
                  :disabled="saving"
                  @update:checked="formData.status = $event ? 'active' : 'inactive'"
                />
              </div>

              <div class="flex items-center justify-between rounded-lg border p-4">
                <div class="space-y-0.5">
                  <UiLabel class="text-base">
                    置顶公告
                  </UiLabel>
                  <p class="text-sm text-muted-foreground">
                    置顶的公告将在应用内优先显示
                  </p>
                </div>
                <UiSwitch v-model:checked="formData.is_top" :disabled="saving" />
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Eye class="size-5" />
                预览
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">所属应用</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">公告标题</span>
                  <span class="truncate max-w-[120px]">{{ formData.title || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">公告类型</span>
                  <div class="flex items-center gap-1.5">
                    <span class="w-2 h-2 rounded-full" :class="selectedType?.color" />
                    <span>{{ selectedType?.label || '-' }}</span>
                  </div>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">发布状态</span>
                  <span>{{ formData.status === 'active' ? '启用' : '禁用' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">是否置顶</span>
                  <span>{{ formData.is_top ? '是' : '否' }}</span>
                </div>
              </div>

              <div class="border-t pt-4 mt-4">
                <p class="text-sm text-muted-foreground mb-2">
                  内容预览
                </p>
                <div class="rounded-lg bg-muted/50 p-3 min-h-[80px]">
                  <p class="text-sm whitespace-pre-wrap">
                    {{ formData.content || '暂无内容' }}
                  </p>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardContent class="pt-6">
              <div class="flex flex-col gap-3">
                <UiButton
                  class="w-full"
                  size="lg"
                  :disabled="saving || !formData.application_id || !formData.title || !formData.content"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Send v-else class="mr-2 h-4 w-4" />
                  发布公告
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  取消
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
