<script setup lang="ts">
import { Check, Info, Loader2, Settings2 } 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: number
  name: string
}

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

const form = ref({
  name: '',
  application_id: '',
  permissions: [] as string[],
  enabled: true,
})

const permissionGroups = computed(() => [
  {
    name: t('admin.extension.apiKeys.permissions.groups.user'),
    permissions: [
      { value: 'user.read', label: t('admin.extension.apiKeys.permissions.userRead'), description: t('admin.extension.apiKeys.permissions.userReadDesc') },
      { value: 'user.list', label: t('admin.extension.apiKeys.permissions.userList'), description: t('admin.extension.apiKeys.permissions.userListDesc') },
      { value: 'user.recharge', label: t('admin.extension.apiKeys.permissions.userRecharge'), description: t('admin.extension.apiKeys.permissions.userRechargeDesc') },
      { value: 'user.deduct', label: t('admin.extension.apiKeys.permissions.userDeduct'), description: t('admin.extension.apiKeys.permissions.userDeductDesc') },
      { value: 'user.variables', label: t('admin.extension.apiKeys.permissions.userVariables'), description: t('admin.extension.apiKeys.permissions.userVariablesDesc') },
    ],
  },
  {
    name: t('admin.extension.apiKeys.permissions.groups.card'),
    permissions: [
      { value: 'card.read', label: t('admin.extension.apiKeys.permissions.cardRead'), description: t('admin.extension.apiKeys.permissions.cardReadDesc') },
      { value: 'card.generate', label: t('admin.extension.apiKeys.permissions.cardGenerate'), description: t('admin.extension.apiKeys.permissions.cardGenerateDesc') },
    ],
  },
  {
    name: t('admin.extension.apiKeys.permissions.groups.notification'),
    permissions: [
      { value: 'notification.send', label: t('admin.extension.apiKeys.permissions.notificationSend'), description: t('admin.extension.apiKeys.permissions.notificationSendDesc') },
    ],
  },
  {
    name: t('admin.extension.apiKeys.permissions.groups.app'),
    permissions: [
      { value: 'app.info', label: t('admin.extension.apiKeys.permissions.appInfo'), description: t('admin.extension.apiKeys.permissions.appInfoDesc') },
      { value: 'app.stats', label: t('admin.extension.apiKeys.permissions.appStats'), description: t('admin.extension.apiKeys.permissions.appStatsDesc') },
      { value: 'app.variables', label: t('admin.extension.apiKeys.permissions.appVariables'), description: t('admin.extension.apiKeys.permissions.appVariablesDesc') },
    ],
  },
])

const filteredApplications = computed(() => {
  return applications.value.map(app => ({
    label: app.name,
    value: String(app.id),
  }))
})

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

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

function togglePermission(permission: string) {
  const index = form.value.permissions.indexOf(permission)
  if (index > -1) {
    form.value.permissions.splice(index, 1)
  }
  else {
    form.value.permissions.push(permission)
  }
}

function selectAllInGroup(permissions: { value: string }[]) {
  for (const perm of permissions) {
    if (!form.value.permissions.includes(perm.value)) {
      form.value.permissions.push(perm.value)
    }
  }
}

function deselectAllInGroup(permissions: { value: string }[]) {
  for (const perm of permissions) {
    const index = form.value.permissions.indexOf(perm.value)
    if (index > -1) {
      form.value.permissions.splice(index, 1)
    }
  }
}

async function handleSubmit() {
  if (!form.value.name) {
    toast.error(t('admin.extension.apiKeys.create.nameRequired'))
    return
  }
  if (!form.value.application_id) {
    toast.error(t('admin.extension.apiKeys.create.selectAppRequired'))
    return
  }
  if (form.value.permissions.length === 0) {
    toast.error(t('admin.extension.apiKeys.create.permissionsRequired'))
    return
  }

  saving.value = true
  try {
    await api.post('/dev/extension/api-keys', {
      name: form.value.name,
      application_id: Number.parseInt(form.value.application_id),
      permissions: form.value.permissions,
      enabled: form.value.enabled,
    })
    toast.success(t('admin.extension.apiKeys.create.submitSuccess'))
    router.push('/admin/extension')
  }
  catch (error: any) {
    console.error('创建API密钥失败:', error)
    toast.error(error.message || t('admin.extension.apiKeys.create.submitFailed'))
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    :title="t('admin.extension.apiKeys.create.title')"
    :description="t('admin.extension.apiKeys.create.description')"
    :breadcrumbs="[
      { title: t('admin.extension.title'), href: '/admin/extension' },
      { title: t('admin.extension.apiKeys.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">
                <Settings2 class="size-5" />
                {{ t('admin.extension.apiKeys.create.title') }}
              </UiCardTitle>
              <UiCardDescription>{{ t('admin.extension.apiKeys.create.description') }}</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-2">
                <UiLabel for="name">
                  {{ t('admin.extension.apiKeys.create.name') }} *
                </UiLabel>
                <UiInput
                  id="name"
                  v-model="form.name"
                  :placeholder="t('admin.extension.apiKeys.create.namePlaceholder')"
                />
              </div>

              <div class="space-y-2">
                <UiLabel for="application">
                  {{ t('admin.extension.apiKeys.create.application') }} *
                </UiLabel>
                <UiSelect v-model="form.application_id">
                  <UiSelectTrigger>
                    <UiSelectValue :placeholder="t('admin.extension.apiKeys.create.selectAppPlaceholder')" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in filteredApplications" :key="app.value" :value="app.value">
                      {{ app.label }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
              </div>

              <div class="space-y-4">
                <div class="flex items-center justify-between">
                  <UiLabel>{{ t('admin.extension.apiKeys.create.permissions') }} *</UiLabel>
                  <div class="flex gap-2">
                    <UiButton variant="outline" size="sm" @click="form.permissions = permissionGroups.flatMap(g => g.permissions.map(p => p.value))">
                      {{ t('admin.extension.apiKeys.create.selectAll') }}
                    </UiButton>
                    <UiButton variant="outline" size="sm" @click="form.permissions = []">
                      {{ t('admin.extension.apiKeys.create.deselectAll') }}
                    </UiButton>
                  </div>
                </div>

                <div v-for="group in permissionGroups" :key="group.name" class="space-y-2">
                  <div class="flex items-center justify-between">
                    <h4 class="text-sm font-medium">
                      {{ group.name }}
                    </h4>
                    <div class="flex gap-1">
                      <UiButton variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="selectAllInGroup(group.permissions)">
                        {{ t('admin.extension.apiKeys.create.selectAll') }}
                      </UiButton>
                      <UiButton variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="deselectAllInGroup(group.permissions)">
                        {{ t('admin.extension.apiKeys.create.deselectAll') }}
                      </UiButton>
                    </div>
                  </div>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                    <div
                      v-for="perm in group.permissions"
                      :key="perm.value"
                      class="flex items-start space-x-2 p-3 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                      :class="{ 'bg-primary/10 border-primary': form.permissions.includes(perm.value) }"
                      @click="togglePermission(perm.value)"
                    >
                      <UiCheckbox
                        :checked="form.permissions.includes(perm.value)"
                        class="mt-0.5"
                        @update:checked="togglePermission(perm.value)"
                      />
                      <div class="flex-1">
                        <div class="text-sm font-medium">
                          {{ perm.label }}
                        </div>
                        <div class="text-xs text-muted-foreground">
                          {{ perm.description }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="flex items-center space-x-2">
                <UiSwitch id="enabled" v-model:checked="form.enabled" />
                <UiLabel for="enabled">
                  {{ t('admin.extension.apiKeys.create.enabled') }}
                </UiLabel>
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Info class="size-5" />
                {{ t('admin.extension.apiKeys.create.preview') || '预览' }}
              </UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.apiKeys.create.name') }}</span>
                  <span>{{ form.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.apiKeys.create.application') }}</span>
                  <span>{{ selectedApplication?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">{{ t('admin.extension.apiKeys.create.permissions') }}</span>
                  <span>{{ form.permissions.length }} {{ t('admin.extension.apiKeys.create.selected') || '已选择' }}</span>
                </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.name || !form.application_id || form.permissions.length === 0"
                  @click="handleSubmit"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Check v-else class="mr-2 h-4 w-4" />
                  {{ t('admin.extension.apiKeys.create.submitBtn') }}
                </UiButton>
                <UiButton
                  variant="outline"
                  class="w-full"
                  @click="router.back()"
                >
                  {{ t('admin.extension.apiKeys.create.cancelBtn') }}
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
