<script setup lang="ts">
import { AppWindow, Check, Globe, Globe2, Info, Loader2, MapPin, ShieldPlus, Smartphone, UserX } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import CountrySelect from '@/components/country-select.vue'
import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

interface Application {
  id: number
  name: string
  app_key: string
}

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

const ruleId = computed(() => route.params.id as string)
const loading = ref(true)
const saving = ref(false)
const applications = ref<Application[]>([])
const loadingApps = ref(true)

const form = ref({
  type: 'device' as 'ip' | 'device' | 'user' | 'region',
  value: '',
  reason: '',
  expires_at: undefined as string | undefined,
  application_id: null as number | null,
  is_global: true,
})

const typeOptions: { value: 'ip' | 'device' | 'user' | 'region', label: string, icon: any, description: string, placeholder: string, scopeType: 'global' | 'app' | 'both' }[] = [
  { value: 'ip', label: 'IP封禁', icon: Globe, description: '封禁特定IP地址或IP段', placeholder: '输入IP地址，如 192.168.1.1 或 192.168.1.0/24', scopeType: 'both' },
  { value: 'device', label: '设备封禁', icon: Smartphone, description: '封禁特定设备指纹', placeholder: '输入设备指纹', scopeType: 'both' },
  { value: 'user', label: '用户封禁', icon: UserX, description: '封禁特定用户账号（需指定应用）', placeholder: '输入用户ID或用户名', scopeType: 'app' },
  { value: 'region', label: '地区封禁', icon: MapPin, description: '封禁特定地区访问', placeholder: '', scopeType: 'both' },
]

const currentTypeInfo = computed(() => {
  return typeOptions.find(t => t.value === form.value.type) || typeOptions[0]
})

const needApplication = computed(() => {
  return currentTypeInfo.value.scopeType === 'app' || (!form.value.is_global && currentTypeInfo.value.scopeType === 'both')
})

const canSelectScope = computed(() => {
  return currentTypeInfo.value.scopeType === 'both'
})

watch(() => form.value.type, (newType) => {
  const typeInfo = typeOptions.find(t => t.value === newType)
  if (typeInfo) {
    if (typeInfo.scopeType === 'global') {
      form.value.is_global = true
    }
    else if (typeInfo.scopeType === 'app') {
      form.value.is_global = false
    }
  }
}, { immediate: true })

async function fetchRule() {
  loading.value = true
  try {
    const data = await api.get<any>(`/dev/risk-control/rules/${ruleId.value}`)
    const rule = data?.rule || data
    if (rule) {
      form.value.type = rule.type || 'device'
      form.value.value = rule.value || ''
      form.value.reason = rule.reason || ''
      form.value.expires_at = rule.expires_at || undefined
      form.value.application_id = rule.application_id || null
      form.value.is_global = rule.is_global !== false
    }
  }
  catch (error) {
    console.error('获取风控规则失败:', error)
    toast.error('获取风控规则失败')
  }
  finally {
    loading.value = false
  }
}

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

const countries: Record<string, { name: string, flag: string }> = {
  CN: { name: '中国', flag: '🇨🇳' },
  US: { name: '美国', flag: '🇺🇸' },
  JP: { name: '日本', flag: '🇯🇵' },
  KR: { name: '韩国', flag: '🇰🇷' },
  GB: { name: '英国', flag: '🇬🇧' },
  DE: { name: '德国', flag: '🇩🇪' },
  FR: { name: '法国', flag: '🇫🇷' },
  IT: { name: '意大利', flag: '🇮🇹' },
  ES: { name: '西班牙', flag: '🇪🇸' },
  RU: { name: '俄罗斯', flag: '🇷🇺' },
  CA: { name: '加拿大', flag: '🇨🇦' },
  AU: { name: '澳大利亚', flag: '🇦🇺' },
  BR: { name: '巴西', flag: '🇧🇷' },
  IN: { name: '印度', flag: '🇮🇳' },
  MX: { name: '墨西哥', flag: '🇲🇽' },
  NL: { name: '荷兰', flag: '🇳🇱' },
  SG: { name: '新加坡', flag: '🇸🇬' },
  HK: { name: '中国香港', flag: '🇭🇰' },
  TW: { name: '中国台湾', flag: '🇹🇼' },
  TH: { name: '泰国', flag: '🇹🇭' },
  VN: { name: '越南', flag: '🇻🇳' },
  MY: { name: '马来西亚', flag: '🇲🇾' },
  ID: { name: '印度尼西亚', flag: '🇮🇩' },
  PH: { name: '菲律宾', flag: '🇵🇭' },
  AE: { name: '阿联酋', flag: '🇦🇪' },
  SA: { name: '沙特阿拉伯', flag: '🇸🇦' },
  TR: { name: '土耳其', flag: '🇹🇷' },
  PL: { name: '波兰', flag: '🇵🇱' },
  SE: { name: '瑞典', flag: '🇸🇪' },
  CH: { name: '瑞士', flag: '🇨🇭' },
  AT: { name: '奥地利', flag: '🇦🇹' },
  BE: { name: '比利时', flag: '🇧🇪' },
  DK: { name: '丹麦', flag: '🇩🇰' },
  FI: { name: '芬兰', flag: '🇫🇮' },
  NO: { name: '挪威', flag: '🇳🇴' },
  IE: { name: '爱尔兰', flag: '🇮🇪' },
  PT: { name: '葡萄牙', flag: '🇵🇹' },
  CZ: { name: '捷克', flag: '🇨🇿' },
  RO: { name: '罗马尼亚', flag: '🇷🇴' },
  HU: { name: '匈牙利', flag: '🇭🇺' },
  IL: { name: '以色列', flag: '🇮🇱' },
  ZA: { name: '南非', flag: '🇿🇦' },
  EG: { name: '埃及', flag: '🇪🇬' },
  NG: { name: '尼日利亚', flag: '🇳🇬' },
  AR: { name: '阿根廷', flag: '🇦🇷' },
  CL: { name: '智利', flag: '🇨🇱' },
  CO: { name: '哥伦比亚', flag: '🇨🇴' },
  PE: { name: '秘鲁', flag: '🇵🇪' },
  NZ: { name: '新西兰', flag: '🇳🇿' },
}

function getCountryDisplay(code: string) {
  const country = countries[code]
  return country ? `${country.flag} ${country.name} (${code})` : code
}

async function handleSave() {
  if (!form.value.value.trim()) {
    toast.error('请输入封禁值')
    return
  }

  if (needApplication.value && !form.value.application_id) {
    toast.error('请选择应用')
    return
  }

  saving.value = true
  try {
    const payload: any = {
      type: form.value.type,
      value: form.value.value,
      reason: form.value.reason,
      application_id: needApplication.value ? form.value.application_id : null,
      is_global: form.value.is_global,
    }

    if (form.value.expires_at) {
      payload.expires_at = form.value.expires_at
    }

    await api.put(`/dev/risk-control/rules/${ruleId.value}`, payload)
    toast.success('更新成功')
    router.push('/admin/risk-control')
  }
  catch (error: any) {
    console.error('更新风控规则失败:', error)
    toast.error(error.message || '更新失败')
  }
  finally {
    saving.value = false
  }
}

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

<template>
  <BasicPage
    title="编辑规则"
    description="修改风控规则配置"
    :breadcrumbs="[
      { title: '风控管理', href: '/admin/risk-control' },
      { title: '编辑规则' },
    ]"
    sticky
  >
    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="size-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else 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">
                <ShieldPlus class="size-5" />
                规则配置
              </UiCardTitle>
              <UiCardDescription>配置风控规则的类型和封禁目标</UiCardDescription>
            </UiCardHeader>
            <UiCardContent class="space-y-6">
              <div class="space-y-3">
                <UiLabel>规则类型</UiLabel>
                <div class="grid gap-3 sm:grid-cols-2">
                  <button
                    v-for="option in typeOptions"
                    :key="option.value"
                    type="button"
                    class="flex items-start gap-3 p-4 rounded-lg border text-left transition-all duration-200"
                    :class="form.type === option.value ? 'border-primary bg-primary/5 ring-1 ring-primary' : 'border-border hover:border-primary/50 hover:bg-muted/50'"
                    @click="form.type = option.value"
                  >
                    <component
                      :is="option.icon"
                      class="size-5 mt-0.5 transition-colors duration-200"
                      :class="form.type === option.value ? 'text-primary' : 'text-muted-foreground'"
                    />
                    <div>
                      <div
                        class="font-medium transition-colors duration-200"
                        :class="form.type === option.value ? 'text-primary' : ''"
                      >
                        {{ option.label }}
                      </div>
                      <div class="text-sm text-muted-foreground">
                        {{ option.description }}
                      </div>
                    </div>
                  </button>
                </div>
              </div>

              <div v-if="canSelectScope" class="space-y-3">
                <UiLabel>生效范围</UiLabel>
                <div class="grid gap-3 sm:grid-cols-2">
                  <button
                    type="button"
                    class="flex items-start gap-3 p-4 rounded-lg border text-left transition-all duration-200"
                    :class="form.is_global ? 'border-primary bg-primary/5 ring-1 ring-primary' : 'border-border hover:border-primary/50 hover:bg-muted/50'"
                    @click="form.is_global = true"
                  >
                    <Globe2 class="size-5 mt-0.5 transition-colors duration-200"
                      :class="form.is_global ? 'text-primary' : 'text-muted-foreground'" />
                    <div>
                      <div
                        class="font-medium transition-colors duration-200"
                        :class="form.is_global ? 'text-primary' : ''"
                      >
                        全局封禁
                      </div>
                      <div class="text-sm text-muted-foreground">
                        对所有应用生效
                      </div>
                    </div>
                  </button>
                  <button
                    type="button"
                    class="flex items-start gap-3 p-4 rounded-lg border text-left transition-all duration-200"
                    :class="!form.is_global ? 'border-primary bg-primary/5 ring-1 ring-primary' : 'border-border hover:border-primary/50 hover:bg-muted/50'"
                    @click="form.is_global = false"
                  >
                    <AppWindow class="size-5 mt-0.5 transition-colors duration-200"
                      :class="!form.is_global ? 'text-primary' : 'text-muted-foreground'" />
                    <div>
                      <div
                        class="font-medium transition-colors duration-200"
                        :class="!form.is_global ? 'text-primary' : ''"
                      >
                        应用级封禁
                      </div>
                      <div class="text-sm text-muted-foreground">
                        仅对指定应用生效
                      </div>
                    </div>
                  </button>
                </div>
              </div>

              <div v-if="needApplication" class="space-y-2">
                <UiLabel for="application">
                  目标应用
                </UiLabel>
                <UiSelect v-model="form.application_id" :disabled="loadingApps">
                  <UiSelectTrigger>
                    <UiSelectValue placeholder="选择要封禁的应用" />
                  </UiSelectTrigger>
                  <UiSelectContent>
                    <UiSelectItem v-for="app in applications" :key="app.id" :value="app.id">
                      {{ app.name }}
                    </UiSelectItem>
                  </UiSelectContent>
                </UiSelect>
                <p class="text-xs text-muted-foreground">
                  {{ currentTypeInfo.scopeType === 'app' ? '用户封禁必须指定应用' : '选择要应用此封禁规则的应用' }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel for="value">
                  封禁值
                </UiLabel>
                <CountrySelect
                  v-if="form.type === 'region'"
                  v-model="form.value"
                />
                <UiInput
                  v-else
                  id="value"
                  :key="form.type"
                  v-model="form.value"
                  :placeholder="currentTypeInfo.placeholder"
                />
                <p class="text-xs text-muted-foreground">
                  {{ form.type === 'region' ? '选择要封禁的国家或地区' : '根据规则类型输入对应的封禁目标' }}
                </p>
              </div>

              <div class="space-y-2">
                <UiLabel for="reason">
                  封禁原因
                </UiLabel>
                <UiInput id="reason" v-model="form.reason" placeholder="输入封禁原因（可选）" />
              </div>

              <div class="space-y-2">
                <UiLabel for="expires">
                  过期时间
                </UiLabel>
                <UiDatePickerDateTimePicker v-model="form.expires_at" placeholder="选择过期时间" />
                <p class="text-xs text-muted-foreground">
                  留空表示永久封禁
                </p>
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Info 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 class="flex items-center gap-1">
                    <component :is="form.is_global ? Globe2 : AppWindow" class="size-4" />
                    {{ form.is_global ? '全局封禁' : '应用级封禁' }}
                  </span>
                </div>
                <div v-if="needApplication" class="flex justify-between text-sm">
                  <span class="text-muted-foreground">目标应用</span>
                  <span>{{ applications.find(a => a.id === form.application_id)?.name || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">规则类型</span>
                  <span class="flex items-center gap-1">
                    <component :is="currentTypeInfo.icon" class="size-4" />
                    {{ currentTypeInfo.label }}
                  </span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">封禁值</span>
                  <span class="font-mono">
                    {{ form.type === 'region' && form.value ? getCountryDisplay(form.value) : (form.value || '-') }}
                  </span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">封禁原因</span>
                  <span>{{ form.reason || '-' }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">过期时间</span>
                  <span>{{ form.expires_at || '永久' }}</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.value.trim()"
                  @click="handleSave"
                >
                  <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
                  <Check 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>
