import { View, Text, Image, Button } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { distributorInvite } from '../../api'
import './invite.scss'

export default function Invite() {
  const [qrCode, setQrCode] = useState('')
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    fetchQr()
  })

  const fetchQr = async () => {
    try {
      const res: any = await distributorInvite()
      setQrCode(res.qr_code_url)
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '获取二维码失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const saveImage = () => {
    if (!qrCode) return
    Taro.downloadFile({
      url: qrCode,
      success: (res) => {
        Taro.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => Taro.showToast({ title: '已保存', icon: 'success' }),
          fail: () => Taro.showToast({ title: '保存失败', icon: 'none' })
        })
      }
    })
  }

  return (
    <View className='page-container'>
      <View className='qr-card'>
        {loading ? (
            <View className='qr-img' style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Text>Loading...</Text>
            </View>
        ) : (
            <Image src={qrCode} className='qr-img' mode='aspectFit' />
        )}
        <Text className='tip'>扫码加入我的团队{'\n'}一起推广赚佣金</Text>
      </View>

      <Button className='btn-save' onClick={saveImage} disabled={!qrCode}>保存二维码</Button>
    </View>
  )
}
