import { View, Text, Button } from '@tarojs/components'
import Taro, { useRouter, useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { getOrder, prepayMiniprogram } from '../../api'
import './payment.scss'

export default function Payment() {
  const router = useRouter()
  const { id } = router.params
  const [order, setOrder] = useState<any>(null)
  const [loading, setLoading] = useState(false)

  useLoad(async () => {
    if (id) {
        try {
            const res = await getOrder(Number(id))
            setOrder(res)
        } catch (e) {
            console.error(e)
        }
    }
  })

  const handlePay = async () => {
    if (!order) return
    setLoading(true)
    try {
        const params = await prepayMiniprogram(order.id)
        
        await Taro.requestPayment({
            timeStamp: params.timeStamp,
            nonceStr: params.nonceStr,
            package: params.package,
            signType: params.signType,
            paySign: params.paySign
        })
        
        Taro.showToast({ title: '支付成功', icon: 'success' })
        setTimeout(() => {
            Taro.redirectTo({ url: '/pages/order/list' })
        }, 1500)
        
    } catch (err: any) {
        console.error(err)
        if (err.errMsg && err.errMsg.indexOf('cancel') > -1) {
             Taro.showToast({ title: '取消支付', icon: 'none' })
        } else {
             Taro.showToast({ title: '支付失败', icon: 'none' })
        }
    } finally {
        setLoading(false)
    }
  }

  if (!order) return <View>Loading...</View>

  return (
    <View className='page-container'>
        <View className='status-header'>
            <Text className='amount'>¥{order.total_price}</Text>
            <Text className='desc'>订单待支付</Text>
        </View>

        <View className='info-card'>
            <View className='row'>
                <Text className='label'>订单编号</Text>
                <Text className='value'>{order.out_trade_no || order.id}</Text>
            </View>
            <View className='row'>
                <Text className='label'>商品名称</Text>
                <Text className='value'>{order.config_name} x {order.quantity}</Text>
            </View>
        </View>

        <View className='btn-area safe-area-bottom'>
            <Button className='btn-pay' onClick={handlePay} loading={loading}>微信支付</Button>
        </View>
    </View>
  )
}
