<script setup lang="ts">
import { AlertCircle, ArrowDown, ArrowUp, CheckCircle, FileText, Info, Loader2, Minus, Send, Server, Smartphone, Upload, X } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

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

const router = useRouter()
const { t } = useI18n()

interface Application {
  id: string
  name: string
  user_id: string
}

const saving = ref(false)
const applications = ref<Application[]>([])
const form = ref({
  type: 'system' as 'system' | 'application',
  application_id: '',
  title: '',
  priority: 'normal' as 'low' | 'normal' | 'high' | 'urgent',
  content: '',
  images: [] as File[],
  imagePreviews: [] as string[],
})

const currentUserId = computed(() => {
  const userStr = localStorage.getItem('user')
  if (!userStr)
    return null
  try {
    const user = JSON.parse(userStr)
    return user?.id
  }
  catch {
    return null
  }
})

const filteredApplications = computed(() => {
  if (!currentUserId.value)
    return []
  return applications.value.filter(app => String(app.user_id) !== String(currentUserId.value))
})

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

function handleImageUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (files) {
    const newFiles = Array.from(files).filter(file => file.type.startsWith('image/'))
    if (newFiles.length + form.value.images.length > 5) {
      toast.error(t('admin.tickets.create.maxImages'))
      return
    }
    newFiles.forEach((file) => {
      form.value.images.push(file)
      form.value.imagePreviews.push(URL.createObjectURL(file))
    })
  }
}

function removeImage(index: number) {
  form.value.images.splice(index, 1)
  form.value.imagePreviews.splice(index, 1)
}

async function handleSubmit() {
  if (!form.value.title.trim()) {
    toast.error(t('admin.tickets.create.titleRequired'))
    return
  }
  if (!form.value.content.trim()) {
    toast.error(t('admin.tickets.create.descriptionRequired'))
    return
  }
  if (form.value.type === 'application' && !form.value.application_id) {
    toast.error(t('admin.tickets.create.selectAppRequired'))
    return
  }

  saving.value = true
  try {
    const formData = new FormData()
    formData.append('type', form.value.type)
    formData.append('title', form.value.title)
    formData.append('priority', form.value.priority)
    formData.append('content', form.value.content)
    if (form.value.type === 'application' && form.value.application_id) {
      formData.append('application_id', form.value.application_id)
    }
    form.value.images.forEach((file, index) => {
      formData.append(`images[${index}]`, file)
    })

    await api.postFormData('/dev/tickets', formData)
    toast.success(t('admin.tickets.create.submitSuccess'))
    router.push('/admin/tickets')
  }
  catch (error: any) {
    console.error('创建工单失败:', error)
    toast.error(error.message || t('admin.tickets.create.submitFailed'))
  }
  finally {
    saving.value = false
  }
}

function handleCancel() {
  router.back()
}

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

<template>
  <BasicPage
    :title="t('admin.tickets.create.title')"
    :description="t('admin.tickets.create.description')"
    :breadcrumbs="[
      { title: t('admin.tickets.title'), href: '/admin/tickets' },
      { title: t('admin.tickets.create.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">
                <FileText class="size-5" />
                {{ t('admin.tickets.create.config') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.tickets.create.configDesc') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="ticketType">
                  {{ t('admin.tickets.create.ticketTypeLabel') }} *
                </UiLabel>
                <UiSelect v-model="form.type">
                  <UiSelectTrigger id="ticketType">
                    <UiSelectValue :placeholder="t('admin.tickets.create.ticketTypePlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="system">
                      <div class="flex items-center gap-2">
                        <Server class="size-4 text-muted-foreground" />
                        {{ t('admin.tickets.create.ticketTypeSystem') }}
                      </div>
                    </UiSelectItem>
                    <UiSelectItem value="application">
                      <div class="flex items-center gap-2">
                        <Smartphone class="size-4 text-muted-foreground" />
                        {{ t('admin.tickets.create.ticketTypeApplication') }}
                      </div>
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div v-if="form.type === 'application'" class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.tickets.create.applicationLabel') }} *
                </UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger id="application">
                    <UiSelectValue :placeholder="t('admin.tickets.create.selectApplication')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in filteredApplications" :key="app.id" :value="String(app.id)">
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p v-if="filteredApplications.length === 0" class="text-xs text-muted-foreground">
                  {{ t('admin.tickets.create.noApplications') }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel for="title">
                  {{ t('admin.tickets.create.titleLabel') }} *
                </UiLabel>
                <UiInput
                  id="title"
                  v-model="form.title"
                  :placeholder="t('admin.tickets.create.titlePlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="priority">
                  {{ t('admin.tickets.create.priorityLabel') }}
                </UiLabel>
                <UiSelect v-model="form.priority">
                  <UiSelectTrigger id="priority">
                    <UiSelectValue :placeholder="t('admin.tickets.create.priorityPlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem value="low">
                      <div class="flex items-center gap-2">
                        <ArrowDown class="size-4 text-muted-foreground" />
                        {{ t('admin.tickets.priority.low') }}
                      </div>
                    </UiSelectItem>
                    <UiSelectItem value="normal">
                      <div class="flex items-center gap-2">
                        <Minus class="size-4 text-muted-foreground" />
                        {{ t('admin.tickets.priority.normal') }}
                      </div>
                    </UiSelectItem>
                    <UiSelectItem value="high">
                      <div class="flex items-center gap-2">
                        <ArrowUp class="size-4 text-muted-foreground" />
                        {{ t('admin.tickets.priority.high') }}
                      </div>
                    </UiSelectItem>
                    <UiSelectItem value="urgent">
                      <div class="flex items-center gap-2">
                        <AlertCircle class="size-4 text-muted-foreground" />
                        {{ t('admin.tickets.priority.urgent') }}
                      </div>
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-2">
                <UiLabel for="description">
                  {{ t('admin.tickets.create.descriptionLabel') }} *
                </UiLabel>
                <UiTextarea
                  id="description"
                  v-model="form.content"
                  :placeholder="t('admin.tickets.create.descriptionPlaceholder')"
                  rows="8"
                />
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.tickets.create.descriptionHint') }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel>
                  {{ t('admin.tickets.create.imagesLabel') }}
                </UiLabel>
                <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-4">
                  <div
                    v-for="(preview, index) in form.imagePreviews"
                    :key="index"
                    class="relative aspect-square rounded-lg border-2 border-dashed overflow-hidden group"
                  >
                    <img :src="preview" class="w-full h-full object-cover">
                    <UiButton
                      variant="destructive"
                      size="icon"
                      class="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity"
                      @click="removeImage(index)"
                    >
                      <X class="h-3 w-3" />
                    </UiButton>
                  </div>
                  <label
                    v-if="form.imagePreviews.length < 5"
                    class="flex items-center justify-center aspect-square rounded-lg border-2 border-dashed cursor-pointer hover:bg-accent/50 transition-colors"
                  >
                    <input
                      type="file"
                      accept="image/*"
                      multiple
                      class="hidden"
                      @change="handleImageUpload"
                    >
                    <Upload class="w-6 h-6 text-muted-foreground" />
                  </label>
                </div>
                <p class="text-xs text-muted-foreground">
                  {{ t('admin.tickets.create.imagesHint') }}
                </p>
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Info class="size-5" />
                {{ t('admin.tickets.create.tips') }}
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3 text-sm">
                <div class="flex gap-3">
                  <CheckCircle class="size-5 text-primary flex-shrink-0" />
                  <p>{{ t('admin.tickets.create.tip1') }}</p>
                </div>
                <div class="flex gap-3">
                  <CheckCircle class="size-5 text-primary flex-shrink-0" />
                  <p>{{ t('admin.tickets.create.tip2') }}</p>
                </div>
                <div class="flex gap-3">
                  <CheckCircle class="size-5 text-primary flex-shrink-0" />
                  <p>{{ t('admin.tickets.create.tip3') }}</p>
                </div>
                <div class="flex gap-3">
                  <CheckCircle class="size-5 text-primary flex-shrink-0" />
                  <p>{{ t('admin.tickets.create.tip4') }}</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 || !form.title.trim() || !form.content.trim() || (form.type === 'application' && !form.application_id)"
                  @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" />
                  {{ t('admin.tickets.create.submit') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="handleCancel"
                >
                  {{ t('admin.tickets.create.cancel') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
