import { computed, ref } from 'vue'

import { showError, showPrompt, showSuccess, isFeedbackDismissed } from '@/lib/feedback'
import {
  deleteAdminCloudtentaclesSource,
  saveAdminCloudtentaclesSourceConfig,
  sendAdminCloudtentaclesSmsCode,
  testAdminCloudtentaclesLogin,
  validateAdminCloudtentaclesSession,
} from '@/services/admin'
import type {
  AdminCloudtentaclesLoginTestResult,
  AdminCloudtentaclesPersistedSession,
  AdminCloudtentaclesSendSmsResult,
  AdminCloudtentaclesSourceItem,
  AdminCloudtentaclesSessionsMap,
  AdminCloudtentaclesSourceConfigResponse,
  AdminCloudtentaclesSourcesConfig,
  AdminCloudtentaclesValidateSessionResult,
} from '@/types/admin'

import type { CloudtentaclesForm } from './useCloudtentaclesDebugActions'
import { useCloudtentaclesDebugActions } from './useCloudtentaclesDebugActions'

export function useAdminCloudtentaclesPlatform() {
  const cloudtentaclesFilePath = ref('')
  const cloudtentaclesSessionFilePath = ref('')
  const selectedSourceKey = ref('default')

  const sources = ref<AdminCloudtentaclesSourceItem[]>([])
  const sessions = ref<AdminCloudtentaclesSessionsMap>({})

  const cloudtentaclesForm = ref<CloudtentaclesForm>({
    baseUrl: 'https://123.207.217.176',
    username: '',
    password: '',
    phone: '',
    code: '',
    token: '',
    vnKey: '1',
    vnId: 0,
    skuId: 5,
    skuCount: 1,
    deviceId: '-',
    deviceType: 0,
  })
  const cloudtentaclesSaving = ref(false)
  const cloudtentaclesSendingSms = ref(false)
  const cloudtentaclesTesting = ref(false)
  const cloudtentaclesValidating = ref(false)
  const cloudtentaclesResultError = ref('')
  const cloudtentaclesSmsResult = ref<AdminCloudtentaclesSendSmsResult | null>(null)
  const cloudtentaclesLoginResult = ref<AdminCloudtentaclesLoginTestResult | null>(null)
  const cloudtentaclesValidateResult = ref<AdminCloudtentaclesValidateSessionResult | null>(null)
  const cloudtentaclesPersistedSession = ref<AdminCloudtentaclesPersistedSession | null>(null)

  const debugActions = useCloudtentaclesDebugActions(
    cloudtentaclesForm,
    cloudtentaclesResultError,
    selectedSourceKey,
  )

  const sourceOptions = computed(() => sources.value.map((s) => ({ key: s.key, label: s.label })))

  const currentSource = computed(
    () => sources.value.find((s) => s.key === selectedSourceKey.value) || sources.value[0],
  )

  const currentSession = computed(() => sessions.value[selectedSourceKey.value] || null)

  const cloudtentaclesStats = computed(() => ({
    hasCredential: Boolean(
      cloudtentaclesForm.value.username.trim() &&
        cloudtentaclesForm.value.password.trim() &&
        cloudtentaclesForm.value.phone.trim(),
    ),
    smsSent: Boolean(cloudtentaclesSmsResult.value),
    validated: Boolean(cloudtentaclesValidateResult.value || cloudtentaclesLoginResult.value),
    sourceCount: sources.value.length,
  }))

  function hydrateCloudtentaclesConfig(data: AdminCloudtentaclesSourceConfigResponse) {
    cloudtentaclesFilePath.value = data.filePath
    cloudtentaclesSessionFilePath.value = data.sessionFilePath
    sources.value = data.sources || []
    sessions.value = data.sessions || {}

    // Ensure 'default' always exists
    if (!sources.value.length) {
      sources.value.push({
        key: 'default',
        label: '默认账号',
        baseUrl: 'https://123.207.217.176',
        username: '',
        password: '',
        phone: '',
        deviceId: '-',
        deviceType: 0,
      })
    }

    // Default selectedSourceKey to 'default' or first source
    if (!sources.value.find((s) => s.key === selectedSourceKey.value)) {
      selectedSourceKey.value = sources.value[0].key
    }

    // Hydrate form from the currently selected source
    hydrateFormFromSource(selectedSourceKey.value)
  }

  function hydrateFormFromSource(sourceKey: string) {
    const source = sources.value.find((s) => s.key === sourceKey)
    const session = sessions.value[sourceKey]
    if (source) {
      cloudtentaclesForm.value = {
        baseUrl: source.baseUrl || 'https://123.207.217.176',
        username: source.username || '',
        password: source.password || '',
        phone: source.phone || '',
        code: '',
        token: session?.token || '',
        vnKey: '1',
        vnId: 0,
        skuId: 5,
        skuCount: 1,
        deviceId: source.deviceId || '-',
        deviceType: source.deviceType || 0,
      }
    }
    cloudtentaclesPersistedSession.value = session || null
  }

  function switchSource(sourceKey: string) {
    selectedSourceKey.value = sourceKey
    // Clear transient results when switching
    cloudtentaclesSmsResult.value = null
    cloudtentaclesLoginResult.value = null
    cloudtentaclesValidateResult.value = null
    cloudtentaclesResultError.value = ''
    hydrateFormFromSource(sourceKey)
  }

  async function addSource() {
    try {
      const result = await showPrompt(
        '请输入新账号名称（例如：运营号、客服号）',
        '新增 cloudtentacles 账号',
        {
          inputPattern: /\S/,
          inputErrorMessage: '账号名称不能为空',
        },
      )
      const trimmed = (result.value as string).trim()
      if (!trimmed) {
        showError('账号名称不能为空')
        return
      }
      // Generate a URL-safe key from the label, ensure uniqueness
      const baseKey = trimmed.replace(/[^a-zA-Z0-9\u4e00-\u9fff_]/g, '_').toLowerCase()
      let newKey = baseKey
      let counter = 2
      while (sources.value.some((s) => s.key === newKey)) {
        newKey = `${baseKey}_${counter++}`
      }
      const newSource: AdminCloudtentaclesSourceItem = {
        key: newKey,
        label: trimmed,
        baseUrl: 'https://123.207.217.176',
        username: '',
        password: '',
        phone: '',
        deviceId: '-',
        deviceType: 0,
      }
      sources.value.push(newSource)
      selectedSourceKey.value = newKey
      hydrateFormFromSource(newKey)
    } catch (error) {
      if (isFeedbackDismissed(error)) return // user cancelled / closed
      showError(error instanceof Error ? error.message : '新增账号失败')
    }
  }

  async function removeSource(sourceKey: string) {
    if (sourceKey === 'default') {
      showError('默认账号不可删除')
      return
    }

    try {
      cloudtentaclesSaving.value = true
      await deleteAdminCloudtentaclesSource(sourceKey)
      sources.value = sources.value.filter((s) => s.key !== sourceKey)
      delete sessions.value[sourceKey]
      if (selectedSourceKey.value === sourceKey) {
        selectedSourceKey.value = 'default'
        hydrateFormFromSource('default')
      }
      showSuccess('账号已删除')
    } catch (error) {
      showError(error instanceof Error ? error.message : '删除账号失败')
    } finally {
      cloudtentaclesSaving.value = false
    }
  }

  function buildCloudtentaclesConfigPayload(): AdminCloudtentaclesSourcesConfig {
    // Update current source from form
    const current = sources.value.find((s) => s.key === selectedSourceKey.value)
    if (current) {
      current.baseUrl = cloudtentaclesForm.value.baseUrl.trim() || 'https://123.207.217.176'
      current.username = cloudtentaclesForm.value.username.trim()
      current.password = cloudtentaclesForm.value.password.trim()
      current.phone = cloudtentaclesForm.value.phone.trim()
      current.deviceId = cloudtentaclesForm.value.deviceId.trim() || '-'
      current.deviceType = Number(cloudtentaclesForm.value.deviceType || 0)
    }
    return {
      enabled: true,
      sources: sources.value.map((s) => ({
        key: s.key,
        label: s.label,
        baseUrl: s.baseUrl,
        username: s.username,
        password: s.password,
        phone: s.phone,
        deviceId: s.deviceId,
        deviceType: s.deviceType,
      })),
    }
  }

  function buildCloudtentaclesLoginPayload() {
    return {
      ...buildCloudtentaclesSourcePayload(),
      code: cloudtentaclesForm.value.code.trim(),
      sourceKey: selectedSourceKey.value,
    }
  }

  function buildCloudtentaclesSourcePayload() {
    return {
      baseUrl: cloudtentaclesForm.value.baseUrl.trim() || 'https://123.207.217.176',
      username: cloudtentaclesForm.value.username.trim(),
      password: cloudtentaclesForm.value.password.trim(),
      phone: cloudtentaclesForm.value.phone.trim(),
      deviceId: cloudtentaclesForm.value.deviceId.trim() || '-',
      deviceType: Number(cloudtentaclesForm.value.deviceType || 0),
      sourceKey: selectedSourceKey.value,
    }
  }

  function ensureCloudtentaclesBaseFields() {
    if (!cloudtentaclesForm.value.username.trim() || !cloudtentaclesForm.value.phone.trim()) {
      cloudtentaclesResultError.value = '请先填写 cloudtentacles 账号和手机号'
      return false
    }
    return true
  }

  function ensureCloudtentaclesLoginFields() {
    if (
      !cloudtentaclesForm.value.username.trim() ||
      !cloudtentaclesForm.value.password.trim() ||
      !cloudtentaclesForm.value.phone.trim()
    ) {
      cloudtentaclesResultError.value = '请先填写 cloudtentacles 账号、密码和手机号'
      return false
    }

    if (!cloudtentaclesForm.value.code.trim()) {
      cloudtentaclesResultError.value = '请先填写短信验证码'
      return false
    }

    return true
  }

  async function handleCloudtentaclesSaveSource() {
    cloudtentaclesSaving.value = true
    cloudtentaclesResultError.value = ''

    try {
      const response = await saveAdminCloudtentaclesSourceConfig(buildCloudtentaclesConfigPayload())
      cloudtentaclesFilePath.value = response.data.filePath
      cloudtentaclesSessionFilePath.value = response.data.sessionFilePath
      sources.value = response.data.sources
      sessions.value = response.data.sessions
      const session = sessions.value[selectedSourceKey.value]
      cloudtentaclesPersistedSession.value = session || null
      cloudtentaclesForm.value.token = session?.token || ''
      showSuccess('cloudtentacles 履约平台配置已保存')
    } catch (error) {
      cloudtentaclesResultError.value =
        error instanceof Error ? error.message : 'cloudtentacles 配置保存失败'
      showError(cloudtentaclesResultError.value)
    } finally {
      cloudtentaclesSaving.value = false
    }
  }

  async function handleCloudtentaclesSendSmsCode() {
    if (!ensureCloudtentaclesBaseFields()) {
      return
    }

    cloudtentaclesSendingSms.value = true
    cloudtentaclesResultError.value = ''

    try {
      const response = await sendAdminCloudtentaclesSmsCode(buildCloudtentaclesSourcePayload())
      cloudtentaclesSmsResult.value = response.data
      showSuccess('cloudtentacles 短信验证码已发送')
    } catch (error) {
      cloudtentaclesResultError.value =
        error instanceof Error ? error.message : 'cloudtentacles 发送短信验证码失败'
      showError(cloudtentaclesResultError.value)
    } finally {
      cloudtentaclesSendingSms.value = false
    }
  }

  async function handleCloudtentaclesTestLogin() {
    if (!ensureCloudtentaclesLoginFields()) {
      return
    }

    cloudtentaclesTesting.value = true
    cloudtentaclesResultError.value = ''

    try {
      const response = await testAdminCloudtentaclesLogin(buildCloudtentaclesLoginPayload())
      cloudtentaclesLoginResult.value = response.data
      cloudtentaclesForm.value.token = response.data.token || cloudtentaclesForm.value.token
      cloudtentaclesPersistedSession.value = {
        token: response.data.token || '',
        tokenMasked: response.data.session.tokenMasked,
        baseUrl: response.data.baseUrl,
        username: response.data.username,
        phoneMasked: response.data.phoneMasked,
        loggedInAt: response.data.loggedInAt,
        deviceId: cloudtentaclesForm.value.deviceId.trim() || '-',
        deviceType: Number(cloudtentaclesForm.value.deviceType || 0),
        hasToken: Boolean(response.data.token),
      }
      // Update sessions map
      sessions.value[selectedSourceKey.value] = cloudtentaclesPersistedSession.value
      showSuccess('cloudtentacles 登录测试成功')
    } catch (error) {
      cloudtentaclesResultError.value =
        error instanceof Error ? error.message : 'cloudtentacles 登录测试失败'
      showError(cloudtentaclesResultError.value)
    } finally {
      cloudtentaclesTesting.value = false
    }
  }

  async function handleCloudtentaclesValidateSession() {
    const token = cloudtentaclesForm.value.token.trim()
    if (!token) {
      cloudtentaclesResultError.value = '请先填写 token'
      return
    }

    cloudtentaclesValidating.value = true
    cloudtentaclesResultError.value = ''

    try {
      const response = await validateAdminCloudtentaclesSession({
        baseUrl: cloudtentaclesForm.value.baseUrl.trim() || 'https://123.207.217.176',
        token,
        deviceId: cloudtentaclesForm.value.deviceId.trim() || '-',
        deviceType: Number(cloudtentaclesForm.value.deviceType || 0),
        sourceKey: selectedSourceKey.value,
      })
      cloudtentaclesValidateResult.value = response.data
      cloudtentaclesPersistedSession.value = {
        token,
        tokenMasked: response.data.session.tokenMasked,
        baseUrl: response.data.baseUrl,
        username:
          cloudtentaclesPersistedSession.value?.username ||
          cloudtentaclesForm.value.username.trim(),
        phoneMasked: cloudtentaclesPersistedSession.value?.phoneMasked || '',
        loggedInAt: response.data.loggedInAt,
        deviceId: cloudtentaclesForm.value.deviceId.trim() || '-',
        deviceType: Number(cloudtentaclesForm.value.deviceType || 0),
        hasToken: Boolean(token),
      }
      // Update sessions map
      sessions.value[selectedSourceKey.value] = cloudtentaclesPersistedSession.value
      showSuccess('cloudtentacles 会话校验成功')
    } catch (error) {
      cloudtentaclesResultError.value =
        error instanceof Error ? error.message : 'cloudtentacles 会话校验失败'
      showError(cloudtentaclesResultError.value)
    } finally {
      cloudtentaclesValidating.value = false
    }
  }

  return {
    cloudtentaclesFilePath,
    cloudtentaclesSessionFilePath,
    cloudtentaclesForm,
    cloudtentaclesSaving,
    cloudtentaclesSendingSms,
    cloudtentaclesTesting,
    cloudtentaclesValidating,
    cloudtentaclesResultError,
    cloudtentaclesSmsResult,
    cloudtentaclesLoginResult,
    cloudtentaclesValidateResult,
    cloudtentaclesDebugLoading: debugActions.cloudtentaclesDebugLoading,
    cloudtentaclesDebugResult: debugActions.cloudtentaclesDebugResult,
    cloudtentaclesPersistedSession,
    cloudtentaclesStats,
    sources,
    sessions,
    selectedSourceKey,
    sourceOptions,
    currentSource,
    currentSession,
    hydrateCloudtentaclesConfig,
    switchSource,
    addSource,
    removeSource,
    handleCloudtentaclesSaveSource,
    handleCloudtentaclesSendSmsCode,
    handleCloudtentaclesTestLogin,
    handleCloudtentaclesValidateSession,
    handleCloudtentaclesFetchAsset: debugActions.handleCloudtentaclesFetchAsset,
    handleCloudtentaclesFetchCategories: debugActions.handleCloudtentaclesFetchCategories,
    handleCloudtentaclesFetchSkuList: debugActions.handleCloudtentaclesFetchSkuList,
    handleCloudtentaclesBuySku: debugActions.handleCloudtentaclesBuySku,
    handleCloudtentaclesUseSku: debugActions.handleCloudtentaclesUseSku,
    handleCloudtentaclesFetchKnapsack: debugActions.handleCloudtentaclesFetchKnapsack,
    handleCloudtentaclesFetchVnList: debugActions.handleCloudtentaclesFetchVnList,
    handleCloudtentaclesAppointVn: debugActions.handleCloudtentaclesAppointVn,
    handleCloudtentaclesGenerateVnLoginCode: debugActions.handleCloudtentaclesGenerateVnLoginCode,
    handleCloudtentaclesFetchVnCode: debugActions.handleCloudtentaclesFetchVnCode,
    handleCloudtentaclesVerifyVnCode: debugActions.handleCloudtentaclesVerifyVnCode,
    handleCloudtentaclesFetchBindUrl: debugActions.handleCloudtentaclesFetchBindUrl,
    handleCloudtentaclesBackVn: debugActions.handleCloudtentaclesBackVn,
    handleCloudtentaclesRunFullFlow: debugActions.handleCloudtentaclesRunFullFlow,
  }
}
