import { useState, useCallback } from 'react'
import Taro from '@tarojs/taro'

interface UsePaymentOptions {
  onSuccess?: (orderNo: string) => void
  onFail?: (error: any) => void
}

interface UsePaymentReturn {
  loading: boolean
  error: string | null
  requestPayment: (payParams: {
    timeStamp: string
    nonceStr: string
    package: string
    signType: string
    paySign: string
    orderNo?: string
  }) => Promise<boolean>
  createAndPay: (createOrderFn: () => Promise<any>) => Promise<boolean>
}

export function usePayment(options: UsePaymentOptions = {}): UsePaymentReturn {
  const { onSuccess, onFail } = options
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const requestPayment = useCallback(async (payParams: {
    timeStamp: string
    nonceStr: string
    package: string
    signType: string
    paySign: string
    orderNo?: string
  }): Promise<boolean> => {
    setLoading(true)
    setError(null)
    try {
      await Taro.requestPayment({
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType as any,
        paySign: payParams.paySign,
      })
      payParams.orderNo && onSuccess?.(payParams.orderNo)
      return true
    } catch (err: any) {
      if (err.errMsg?.includes('cancel')) {
        setError('支付已取消')
      } else {
        setError(err.errMsg || '支付失败')
        onFail?.(err)
      }
      return false
    } finally {
      setLoading(false)
    }
  }, [onSuccess, onFail])

  const createAndPay = useCallback(async (createOrderFn: () => Promise<any>): Promise<boolean> => {
    setLoading(true)
    setError(null)
    try {
      const result = await createOrderFn()
      return await requestPayment(result)
    } catch (err: any) {
      setError(err.message || '创建订单失败')
      onFail?.(err)
      return false
    } finally {
      setLoading(false)
    }
  }, [requestPayment, onFail])

  return { loading, error, requestPayment, createAndPay }
}
