import { useEffect, useRef, useState } from 'react'
import { useGetWebChargeCheckoutResult } from './useWallet'

interface UsePaymentPollingOptions {
  submitId: string | null
  onSuccess?: (data: any) => void
  onError?: (error: any) => void
  onTimeout?: () => void
  maxAttempts?: number // 最大轮询次数，默认 60 次（3分钟）
  interval?: number // 轮询间隔，默认 3000ms
}

export enum PaymentStatus {
  WAITPAY = 'WAITPAY',
  PAID = 'PAID',
  PROCESSING = 'PROCESSING',
  FINISHED = 'FINISHED',
  CLOSED = 'CLOSED',
  REFUNDING = 'REFUNDING',
  REFUNDED = 'REFUNDED',
}

export function usePaymentPolling({
  submitId,
  onSuccess,
  onError,
  onTimeout,
  maxAttempts = 60,
  interval = 5000,
}: UsePaymentPollingOptions) {
  const [isPolling, setIsPolling] = useState(false)
  const [pollingData, setPollingData] = useState<any>(null)
  const [pollingError, setPollingError] = useState<any>(null)
  const [attemptCount, setAttemptCount] = useState(0)

  const { mutateAsync: checkPaymentResult } = useGetWebChargeCheckoutResult()
  const intervalRef = useRef<NodeJS.Timeout | null>(null)
  const timeoutRef = useRef<NodeJS.Timeout | null>(null)

  // 检查支付状态是否为成功状态
  const isPaymentSuccess = (tradeStatus: PaymentStatus) => {
    return tradeStatus === PaymentStatus.PAID || tradeStatus === PaymentStatus.FINISHED
  }

  // 开始轮询
  const startPolling = () => {
    if (!submitId || isPolling) return

    setIsPolling(true)
    setAttemptCount(0)
    setPollingData(null)
    setPollingError(null)

    const poll = async () => {
      try {
        setAttemptCount((prev) => prev + 1)

        const result = await checkPaymentResult({ submitId })
        console.log('result', result)
        setPollingData(result)

        // 检查是否支付成功
        if (isPaymentSuccess(result.tradeStatus as PaymentStatus)) {
          stopPolling()
          onSuccess?.(result)
          return
        }

        // 检查是否达到最大尝试次数
        if (attemptCount + 1 >= maxAttempts) {
          stopPolling()
          onTimeout?.()
          return
        }

        // 继续轮询
        intervalRef.current = setTimeout(poll, interval)
      } catch (error) {
        setPollingError(error)
        onError?.(error)

        // 即使出错也继续轮询，除非达到最大尝试次数
        if (attemptCount + 1 < maxAttempts) {
          intervalRef.current = setTimeout(poll, interval)
        } else {
          stopPolling()
        }
      }
    }

    // 立即执行第一次检查
    poll()
  }

  // 停止轮询
  const stopPolling = () => {
    setIsPolling(false)

    if (intervalRef.current) {
      clearTimeout(intervalRef.current)
      intervalRef.current = null
    }

    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
      timeoutRef.current = null
    }
  }

  // 重置轮询状态
  const resetPolling = () => {
    stopPolling()
    setPollingData(null)
    setPollingError(null)
    setAttemptCount(0)
  }

  // 当 submitId 变化时自动开始轮询
  useEffect(() => {
    if (submitId) {
      startPolling()
    } else {
      resetPolling()
    }

    // 组件卸载时清理
    return () => {
      stopPolling()
    }
  }, [submitId])

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      stopPolling()
    }
  }, [])

  return {
    isPolling,
    pollingData,
    pollingError,
    attemptCount,
    isPaymentSuccess: pollingData ? isPaymentSuccess(pollingData.tradeStatus) : false,
    startPolling,
    stopPolling,
    resetPolling,
  }
}
