import { View, Text, Button, Input } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { distributorInfo, distributorWithdraw } from '../../api'
import './withdraw.scss'

export default function Withdraw() {
  const [balance, setBalance] = useState(0)
  const [amount, setAmount] = useState('')
  const [loading, setLoading] = useState(false)

  useLoad(() => {
    fetchInfo()
  })

  const fetchInfo = async () => {
    try {
      const res: any = await distributorInfo()
      setBalance(Number(res.withdrawable_balance))
    } catch (err) {
      console.error(err)
    }
  }

  const handleWithdraw = async () => {
    const val = Number(amount)
    if (!val || val <= 0) {
      Taro.showToast({ title: '请输入有效金额', icon: 'none' })
      return
    }
    if (val > balance) {
      Taro.showToast({ title: '余额不足', icon: 'none' })
      return
    }

    setLoading(true)
    try {
      await distributorWithdraw(val)
      Taro.showToast({ title: '申请已提交', icon: 'success' })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    } catch (err) {
      Taro.showToast({ title: '提现失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className='page-container'>
      <View className='card'>
        <Text className='label'>提现金额</Text>
        <View className='input-box'>
          <Text className='symbol'>¥</Text>
          <Input 
            className='input' 
            type='digit' 
            value={amount} 
            onInput={(e) => setAmount(e.detail.value)}
            placeholder='0.00'
          />
        </View>
        <View className='balance-tip'>
          <Text>可提现余额 ¥{balance.toFixed(2)}</Text>
          <Text className='all' onClick={() => setAmount(balance.toString())}>全部提现</Text>
        </View>
        
        <Button className='btn-submit' onClick={handleWithdraw} loading={loading}>确认提现</Button>
      </View>
    </View>
  )
}
