import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { appApi, type App } from '@/api/app'
import { ElMessage } from 'element-plus'

const STORAGE_KEY = 'bugcollect_selected_app_key'

export function useBugCollectApp() {
  const route = useRoute()
  const router = useRouter()
  const apps = ref<App[]>([])
  const loadingApps = ref(false)
  const selectedAppKey = ref(localStorage.getItem(STORAGE_KEY) ?? '')
  const serviceEnabled = ref<boolean | null>(null)
  const checkingService = ref(false)
  const applyDialogVisible = ref(false)
  const applyReason = ref('')
  const applyLoading = ref(false)

  const appKey = computed(() => {
    const q = route.query.appKey
    if (typeof q === 'string' && q.trim()) return q.trim()
    return selectedAppKey.value
  })

  // 'no-app' | 'loading' | 'not-enabled' | 'enabled'
  const gateStatus = computed(() => {
    if (!appKey.value) return 'no-app'
    if (checkingService.value || serviceEnabled.value === null) return 'loading'
    return serviceEnabled.value ? 'enabled' : 'not-enabled'
  })

  async function loadApps() {
    loadingApps.value = true
    try {
      const res = await appApi.list()
      apps.value = res.data.data ?? []
    } catch {
      apps.value = []
    } finally {
      loadingApps.value = false
    }
  }

  async function checkService(key: string) {
    if (!key) {
      serviceEnabled.value = null
      return
    }
    checkingService.value = true
    serviceEnabled.value = null
    try {
      const res = await appApi.getServices(key)
      const found = (res.data.data ?? []).find(s => s.serviceType === 'BUG_COLLECT')
      serviceEnabled.value = found?.enabled ?? false
    } catch {
      serviceEnabled.value = false
    } finally {
      checkingService.value = false
    }
  }

  function setApp(key: string) {
    selectedAppKey.value = key
    localStorage.setItem(STORAGE_KEY, key)
    router.replace({ query: { ...route.query, appKey: key } })
  }

  async function submitActivation() {
    if (!appKey.value || !applyReason.value.trim()) return
    applyLoading.value = true
    try {
      await appApi.requestActivation(appKey.value, 'BUG_COLLECT', applyReason.value.trim())
      ElMessage.success('申请已提交，请等待审核')
      applyDialogVisible.value = false
      applyReason.value = ''
    } catch {
      ElMessage.error('申请提交失败，请稍后重试')
    } finally {
      applyLoading.value = false
    }
  }

  watch(appKey, (key) => {
    checkService(key)
  })

  onMounted(() => {
    const q = route.query.appKey
    if (typeof q === 'string' && q.trim()) {
      selectedAppKey.value = q.trim()
      localStorage.setItem(STORAGE_KEY, q.trim())
    }
    loadApps()
    if (appKey.value) checkService(appKey.value)
  })

  return {
    apps,
    loadingApps,
    appKey,
    setApp,
    gateStatus,
    serviceEnabled,
    checkingService,
    applyDialogVisible,
    applyReason,
    applyLoading,
    submitActivation,
  }
}
