import { View, Text, Button } from '@tarojs/components'
import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { getToken, wechatLogin } from '@/services/auth'
import './index.scss'

export default function Login() {
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (getToken()) {
      Taro.reLaunch({ url: '/pages/device/index' })
    }
  }, [])

  const handleLogin = async () => {
    if (submitting) return

    setSubmitting(true)
    Taro.showLoading({ title: '登录中...' })

    try {
      const loginRes = await Taro.login()
      if (!loginRes.code) {
        throw new Error('未获取到微信登录凭证')
      }

      let userInfo:
        | {
            nickName?: string
            avatarUrl?: string
          }
        | null = null

      try {
        const profileRes = await Taro.getUserProfile({
          desc: '用于完善家长资料展示',
        })
        userInfo = profileRes.userInfo || null
      } catch (error) {
        console.log('[login] getUserProfile skipped:', error)
      }

      await wechatLogin({
        code: loginRes.code,
        nickname: userInfo?.nickName,
        avatar_url: userInfo?.avatarUrl,
      })

      if (userInfo) {
        Taro.setStorageSync('userInfo', {
          nickname: userInfo.nickName,
          avatar_url: userInfo.avatarUrl,
        })
      } else {
        Taro.removeStorageSync('userInfo')
      }

      Taro.showToast({ title: '登录成功', icon: 'success' })
      setTimeout(() => {
        Taro.reLaunch({ url: '/pages/device/index' })
      }, 300)
    } catch (error: any) {
      console.error('[login] failed:', error)
      const message = String(error?.message || '登录失败，请重试')
      Taro.showModal({
        title: '登录失败',
        content: message,
        showCancel: false,
      })
    } finally {
      Taro.hideLoading()
      setSubmitting(false)
    }
  }

  return (
    <View className='login-page'>
      <View className='login-header'>
        <View className='logo'>
          <Text className='logo-icon'>🤖</Text>
        </View>
        <Text className='title'>伴伴</Text>
        <Text className='subtitle'>让关爱随时随地</Text>
      </View>

      <View className='login-content'>
        <View className='features'>
          <View className='feature-item'>
            <Text className='feature-icon'>💬</Text>
            <Text className='feature-text'>AI 智能对话</Text>
          </View>
          <View className='feature-item'>
            <Text className='feature-icon'>📍</Text>
            <Text className='feature-text'>实时定位追踪</Text>
          </View>
          <View className='feature-item'>
            <Text className='feature-icon'>🔋</Text>
            <Text className='feature-text'>设备状态监控</Text>
          </View>
        </View>

        <View className='login-btn-wrapper'>
          <Button className='login-btn' loading={submitting} disabled={submitting} onClick={handleLogin}>
            <Text className='btn-icon'>🌐</Text>
            <Text className='btn-text'>{submitting ? '登录中...' : '微信一键登录'}</Text>
          </Button>
        </View>

        <Text className='agreement'>
          登录即代表您同意《用户协议》和《隐私政策》
        </Text>
      </View>
    </View>
  )
}
