import { View, Text, Button } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { distributorInfo } from '../../api'
import './index.scss'

export default function DistributorIndex() {
  const [info, setInfo] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useDidShow(() => {
    fetchInfo()
  })

  const fetchInfo = async () => {
    try {
      const res = await distributorInfo()
      setInfo(res)
    } catch (err: any) {
      if (err.statusCode === 404) {
        // Not registered
        Taro.redirectTo({ url: '/subpackages/distributor/register' })
      } else {
        Taro.showToast({ title: '加载失败', icon: 'none' })
      }
    } finally {
      setLoading(false)
    }
  }

  const goInvite = () => Taro.navigateTo({ url: '/subpackages/distributor/invite' })
  const goWithdraw = () => Taro.navigateTo({ url: '/subpackages/distributor/withdraw' })
  const goTeam = () => Taro.navigateTo({ url: '/subpackages/distributor/team' })
  const goEarnings = () => Taro.navigateTo({ url: '/subpackages/distributor/earnings' })
  const goOrders = () => Taro.navigateTo({ url: '/subpackages/distributor/orders' })

  if (loading) return <View>Loading...</View>
  if (!info) return <View>Error</View>

  return (
    <View className='page-container'>
      <View className='header-card'>
        <Text className='label'>可提现余额</Text>
        <Text className='amount'>¥{info.withdrawable_balance}</Text>
        <Button className='btn-withdraw' onClick={goWithdraw}>提现</Button>
      </View>

      <View className='stats-grid'>
        <View className='item'>
          <Text className='val'>¥{info.total_earnings}</Text>
          <Text className='lbl'>累计收益</Text>
        </View>
        <View className='item'>
          <Text className='val'>Lv.{info.level}</Text>
          <Text className='lbl'>当前等级</Text>
        </View>
        <View className='item'>
          <Text className='val'>{(Number(info.commission_rate) * 100).toFixed(1)}%</Text>
          <Text className='lbl'>分佣比例</Text>
        </View>
      </View>

      <View className='menu-list'>
        <View className='menu-item' onClick={goInvite}>
          <Text>推广二维码</Text>
          <Text className='arrow'>{'>'}</Text>
        </View>
        <View className='menu-item' onClick={goTeam}>
          <Text>我的团队</Text>
          <Text className='arrow'>{'>'}</Text>
        </View>
        <View className='menu-item' onClick={goEarnings}>
          <Text>收益明细</Text>
          <Text className='arrow'>{'>'}</Text>
        </View>
        <View className='menu-item' onClick={goOrders}>
          <Text>分销订单</Text>
          <Text className='arrow'>{'>'}</Text>
        </View>
      </View>
    </View>
  )
}
