import { ref } from 'vue'
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { AssetService, DeviceService } from '@/api/modules'
import { formatRemainingTime, FrontendRateLimitError } from '@/utils/business/apiRateLimit'

/**
 * Asset operations composable
 * Manages asset operation methods (enable/disable cards, device operations, etc.)
 */
export function useAssetOperations(cardInfo: Ref<any>, refreshAssetFn?: () => Promise<void>) {
  // Loading states
  const enableCardLoading = ref(false)
  const startFailureMessage = ref('')
  const disableCardLoading = ref(false)
  const manualDeactivateCardLoading = ref(false)
  const rebootDeviceLoading = ref(false)
  const resetDeviceLoading = ref(false)
  const speedLimitLoading = ref(false)
  const switchCardLoading = ref(false)
  const setWiFiLoading = ref(false)
  const pollingLoading = ref(false)

  /**
   * Enable card
   */
  const enableCard = async () => {
    try {
      await ElMessageBox.confirm('确认要启用此卡吗？', '提示', {
        type: 'warning'
      })

      startFailureMessage.value = ''
      enableCardLoading.value = true
      const res = await AssetService.startAsset(cardInfo.value.iccid, {
        requestOptions: { errorMessageMode: 'none' }
      })
      if (res.code === 0) {
        ElMessage.success('启用成功')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
        return true
      }
      startFailureMessage.value = res.msg || '复机失败，请稍后重试'
      return false
    } catch (error: any) {
      if (error !== 'cancel') {
        if (error instanceof FrontendRateLimitError) {
          ElMessage.warning(`操作过于频繁，请${formatRemainingTime(error.remainingMs)}后再试`)
          return false
        }
        const backendMessage = error?.response?.data?.msg
        startFailureMessage.value =
          typeof backendMessage === 'string' && backendMessage.trim()
            ? backendMessage
            : '复机失败，请稍后重试'
      }
      return false
    } finally {
      enableCardLoading.value = false
    }
  }

  /**
   * Disable card with confirmation
   */
  const disableCard = async () => {
    try {
      await ElMessageBox.confirm('确认要停用此卡吗？', '提示', {
        type: 'warning'
      })

      disableCardLoading.value = true
      const res = await AssetService.stopAsset(cardInfo.value.iccid)
      if (res.code === 0) {
        ElMessage.success('停用成功')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        if (error instanceof FrontendRateLimitError) {
          ElMessage.warning(`操作过于频繁，请${formatRemainingTime(error.remainingMs)}后再试`)
          return
        }
        console.error('停用失败:', error)
      }
    } finally {
      disableCardLoading.value = false
    }
  }

  /**
   * Manually deactivate card with strong warning confirmation
   */
  const manualDeactivateCard = async () => {
    try {
      await ElMessageBox.confirm(
        '手动停用后卡片将永久停用，无法再次使用。此操作不可逆，请谨慎操作。确认要手动停用吗？',
        '警告',
        {
          type: 'error',
          confirmButtonText: '确认停用',
          cancelButtonText: '取消'
        }
      )

      manualDeactivateCardLoading.value = true
      const identifier =
        cardInfo.value.asset_type === 'card' ? cardInfo.value.iccid : cardInfo.value.virtual_no
      const res = await AssetService.deactivateAsset(identifier)
      if (res.code === 0) {
        ElMessage.success('手动停用成功')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('手动停用失败:', error)
        console.log(error?.message || '手动停用失败')
      }
    } finally {
      manualDeactivateCardLoading.value = false
    }
  }

  /**
   * Reboot device with confirmation
   */
  const rebootDevice = async () => {
    try {
      await ElMessageBox.confirm('确认要重启设备吗？', '提示', {
        type: 'warning'
      })

      rebootDeviceLoading.value = true
      const res = await DeviceService.rebootDevice(cardInfo.value.imei)
      if (res.code === 0) {
        ElMessage.success(res.data?.message || '重启指令已发送')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('重启失败:', error)
      }
    } finally {
      rebootDeviceLoading.value = false
    }
  }

  /**
   * Factory reset device with strong warning confirmation
   */
  const resetDevice = async () => {
    try {
      await ElMessageBox.confirm('恢复出厂设置将清除设备所有数据和配置，确认要继续吗？', '警告', {
        type: 'error',
        confirmButtonText: '确认恢复',
        cancelButtonText: '取消'
      })

      resetDeviceLoading.value = true
      const res = await DeviceService.resetDevice(cardInfo.value.imei)
      if (res.code === 0) {
        ElMessage.success(res.data?.message || '恢复出厂设置指令已发送')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('恢复出厂失败:', error)
      }
    } finally {
      resetDeviceLoading.value = false
    }
  }

  /**
   * Set device speed limit
   */
  const setSpeedLimit = async (form: { download_speed: number; upload_speed: number }) => {
    try {
      speedLimitLoading.value = true
      const res = await DeviceService.setSpeedLimit(cardInfo.value.imei, {
        download_speed: form.download_speed,
        upload_speed: form.upload_speed
      })
      if (res.code === 0) {
        ElMessage.success('限速设置成功')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
        return true
      } else {
        ElMessage.error(res.msg || '设置失败')
        return false
      }
    } catch (error: any) {
      console.error('设置限速失败:', error)
      console.log(error?.message || '设置失败')
      return false
    } finally {
      speedLimitLoading.value = false
    }
  }

  /**
   * Switch to different card
   */
  const switchCard = async (form: { target_iccid: string }) => {
    try {
      switchCardLoading.value = true
      const res = await DeviceService.switchCard(cardInfo.value.imei, {
        target_iccid: form.target_iccid
      })
      if (res.code === 0) {
        ElMessage.success('切换SIM卡指令已发送')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
        return true
      } else {
        ElMessage.error(res.msg || '切换失败')
        return false
      }
    } catch (error: any) {
      console.error('切换SIM卡失败:', error)
      console.log(error?.message || '切换失败')
      return false
    } finally {
      switchCardLoading.value = false
    }
  }

  /**
   * Configure WiFi settings
   */
  const setWiFi = async (form: {
    card_no: string
    enabled: boolean
    ssid: string
    password: string
  }) => {
    try {
      setWiFiLoading.value = true
      const res = await DeviceService.setWiFi(cardInfo.value.imei, {
        card_no: form.card_no,
        enabled: form.enabled,
        ssid: form.ssid,
        password: form.password
      })
      if (res.code === 0) {
        ElMessage.success('WiFi设置成功')
        if (refreshAssetFn) {
          await refreshAssetFn()
        }
        return true
      } else {
        ElMessage.error(res.msg || '设置失败')
        return false
      }
    } catch (error: any) {
      console.error('设置WiFi失败:', error)
      console.log(error?.message || '设置WiFi失败')
      return false
    } finally {
      setWiFiLoading.value = false
    }
  }

  /**
   * Update polling status
   */
  const updatePollingStatus = async (enabled: boolean) => {
    if (!cardInfo.value) {
      ElMessage.warning('无法更新轮询状态:缺少资产信息')
      return false
    }

    try {
      pollingLoading.value = true
      const identifier =
        cardInfo.value.asset_type === 'card' ? cardInfo.value.iccid : cardInfo.value.virtual_no

      const response = await AssetService.updatePollingStatus(identifier, {
        enable_polling: enabled
      })

      if (response.code === 0) {
        ElMessage.success(enabled ? '已开启自动轮询' : '已关闭自动轮询')
        // Update local state
        if (cardInfo.value) {
          cardInfo.value.enable_polling = enabled
        }
        return true
      } else {
        ElMessage.error(response.msg || '更新轮询状态失败')
        return false
      }
    } catch (error: any) {
      console.error('更新轮询状态失败:', error)
      console.log(error?.message || '更新轮询状态失败')
      return false
    } finally {
      pollingLoading.value = false
    }
  }

  return {
    // Loading states
    enableCardLoading,
    startFailureMessage,
    disableCardLoading,
    manualDeactivateCardLoading,
    rebootDeviceLoading,
    resetDeviceLoading,
    speedLimitLoading,
    switchCardLoading,
    setWiFiLoading,
    pollingLoading,

    // IoT card operations
    enableCard,
    disableCard,
    manualDeactivateCard,

    // Device operations
    rebootDevice,
    resetDevice,
    setSpeedLimit,
    switchCard,
    setWiFi,

    // Polling
    updatePollingStatus
  }
}
