import { useState } from 'react'
import { Button, Image, Input, Text, View } from '@tarojs/components'
import './index.scss'

interface LoginCardProps {
  onSubmit: (avatarPath: string, nickname: string) => Promise<void> | void
}

export function LoginCard({ onSubmit }: LoginCardProps) {
  const [avatar, setAvatar] = useState('')
  const [nickname, setNickname] = useState('')
  const [submitting, setSubmitting] = useState(false)

  const onChooseAvatar = (e: any) => {
    const url = e?.detail?.avatarUrl
    if (url) setAvatar(url)
  }

  const ready = Boolean(avatar && nickname.trim())

  const submit = async () => {
    if (!ready || submitting) return
    setSubmitting(true)
    try {
      await onSubmit(avatar, nickname.trim())
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <View className='login-card'>
      <Text className='login-card__title'>登录汪圈</Text>
      <Text className='login-card__sub'>授权头像昵称，记录你和毛孩子的日常</Text>

      <Button className='login-card__avatar-btn' openType='chooseAvatar' onChooseAvatar={onChooseAvatar}>
        {avatar ? (
          <Image className='login-card__avatar-img' src={avatar} mode='aspectFill' />
        ) : (
          <View className='login-card__avatar-empty'>
            <Text className='login-card__avatar-plus'>＋</Text>
            <Text className='login-card__avatar-hint'>选择头像</Text>
          </View>
        )}
      </Button>

      <View className='login-card__field'>
        <Input
          className='login-card__input'
          type='nickname'
          placeholder='点此填写昵称'
          placeholderClass='login-card__placeholder'
          value={nickname}
          onInput={e => setNickname(e.detail.value)}
          onBlur={e => setNickname(e.detail.value)}
        />
      </View>

      <View
        className={`login-card__submit ${ready ? '' : 'login-card__submit--disabled'}`}
        onClick={submit}
      >
        {submitting ? '登录中…' : '完成登录'}
      </View>

      <Text className='login-card__tip'>仅用于展示你的头像和昵称，不会获取其他信息</Text>
    </View>
  )
}

export default LoginCard
