import { ref } from 'vue'
import { useAppStore } from '@/stores/app'
import { apiClient } from '@/api/client'

export interface KimiTokenInfo {
  access_token?: string
  refresh_token?: string
  expires_in?: number
  expires_at?: number
  scope?: string
  token_type?: string
  [key: string]: unknown
}

export function useKimiOAuth() {
  const appStore = useAppStore()
  const endpointPrefix = '/admin/kimi'

  // State
  const deviceCode = ref('')
  const userCode = ref('')
  const verificationUri = ref('')
  const verificationUriComplete = ref('')
  const loading = ref(false)
  const error = ref('')
  const sessionId = ref('') // reuse for device_code

  // Reset state
  const resetState = () => {
    deviceCode.value = ''
    userCode.value = ''
    verificationUri.value = ''
    verificationUriComplete.value = ''
    loading.value = false
    error.value = ''
    sessionId.value = ''
  }

  // Initiate device authorization
  const initiateDeviceAuth = async (
    proxyId?: number | null
  ): Promise<boolean> => {
    loading.value = true
    deviceCode.value = ''
    userCode.value = ''
    verificationUri.value = ''
    error.value = ''

    try {
      const payload: Record<string, unknown> = {}
      if (proxyId) {
        payload.proxy_id = proxyId
      }

      const { data } = await apiClient.post<{
        device_code: string
        user_code: string
        verification_uri: string
        verification_uri_complete: string
        expires_in: number
        interval: number
      }>(`${endpointPrefix}/oauth/device-auth`, payload)

      deviceCode.value = data.device_code
      userCode.value = data.user_code
      verificationUri.value = data.verification_uri
      verificationUriComplete.value = data.verification_uri_complete
      sessionId.value = data.device_code
      return true
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to initiate Kimi device auth'
      appStore.showError(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  // Poll for token
  const pollToken = async (): Promise<KimiTokenInfo | null> => {
    if (!deviceCode.value) {
      error.value = 'No device code available'
      return null
    }

    loading.value = true
    error.value = ''

    try {
      const { data } = await apiClient.post<{
        status: string
        access_token?: string
        refresh_token?: string
        expires_in?: number
        expires_at?: number
        scope?: string
        token_type?: string
        message?: string
      }>(`${endpointPrefix}/oauth/token`, {
        device_code: deviceCode.value
      })

      if (data.status === 'pending') {
        return null // Still pending
      }

      return {
        access_token: data.access_token,
        refresh_token: data.refresh_token,
        expires_in: data.expires_in,
        expires_at: data.expires_at,
        scope: data.scope,
        token_type: data.token_type
      }
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to poll Kimi token'
      appStore.showError(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  // Build credentials for Kimi OAuth account
  const buildCredentials = (tokenInfo: KimiTokenInfo): Record<string, unknown> => {
    const creds: Record<string, unknown> = {
      access_token: tokenInfo.access_token,
      expires_at: tokenInfo.expires_at
    }
    if (tokenInfo.refresh_token) {
      creds.refresh_token = tokenInfo.refresh_token
    }
    if (tokenInfo.token_type) {
      creds.token_type = tokenInfo.token_type
    }
    if (tokenInfo.scope) {
      creds.scope = tokenInfo.scope
    }
    return creds
  }

  // Build extra info from token response
  const buildExtraInfo = (_tokenInfo: KimiTokenInfo): Record<string, string> | undefined => {
    return undefined
  }

  // Import local credentials from kimi-cli
  const importLocalCredentials = async (
    credentialsJson: string
  ): Promise<KimiTokenInfo | null> => {
    loading.value = true
    error.value = ''

    try {
      const { data } = await apiClient.post<{
        access_token: string
        refresh_token?: string
        expires_at: number
        scope?: string
        token_type?: string
      }>(`${endpointPrefix}/oauth/import-local`, {
        credentials_json: credentialsJson
      })

      return {
        access_token: data.access_token,
        refresh_token: data.refresh_token,
        expires_at: data.expires_at,
        scope: data.scope,
        token_type: data.token_type
      }
    } catch (err: any) {
      error.value = err.response?.data?.detail || 'Failed to import local credentials'
      appStore.showError(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    deviceCode,
    userCode,
    verificationUri,
    verificationUriComplete,
    loading,
    error,
    sessionId,
    resetState,
    initiateDeviceAuth,
    pollToken,
    buildCredentials,
    buildExtraInfo,
    importLocalCredentials
  }
}
