import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Input, Image } from '@tarojs/components'
import { storeLogin } from '@/api/shop/shopStore'
import { saveStorageByLoginUser } from '@/utils/server'
import './index.scss'

const StoreLogin = () => {
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [showContent, setShowContent] = useState(false)

  useEffect(() => {
    setTimeout(() => setShowContent(true), 100)
  }, [])

  /** 解析 redirect 参数 */
  const router = Taro.getCurrentInstance().router
  const redirectUrl = (() => {
    const raw = (router?.params as Record<string, string> | undefined)?.redirect
    if (!raw) return ''
    try {
      const decoded = decodeURIComponent(raw)
      return decoded.startsWith('/') ? decoded : `/${decoded}`
    } catch {
      return raw.startsWith('/') ? raw : `/${raw}`
    }
  })()

  /** 登录成功后跳转 */
  const navigateAfterLogin = async () => {
    if (!redirectUrl) {
      await Taro.reLaunch({ url: '/pages/index/index' })
      return
    }
    await Taro.redirectTo({ url: redirectUrl })
  }

  /** 账号密码登录 */
  const handleLogin = async () => {
    if (!phone.trim()) {
      Taro.showToast({ title: '请输入手机号', icon: 'none' })
      return
    }
    if (!password.trim()) {
      Taro.showToast({ title: '请输入密码', icon: 'none' })
      return
    }
    if (loading) return

    try {
      setLoading(true)
      const res = await storeLogin({ phone: phone.trim(), password: password.trim() })
      if (res?.access_token) {
        const token = res.access_token
        const user = res.user
        saveStorageByLoginUser(token, user)
        Taro.showToast({ title: '登录成功', icon: 'success' })
        setTimeout(() => navigateAfterLogin(), 800)
      } else {
        Taro.showToast({ title: '登录失败', icon: 'none' })
      }
    } catch (e: any) {
      console.error('门店登录失败:', e)
      Taro.showToast({ title: e?.message || '登录失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className={`page-store-login ${showContent ? 'page-store-login--show' : ''}`}>
      <View className='store-login-bg'>
        <View className='store-login-bg__gradient' />
      </View>

      <View className='store-login-content'>
        <View className='store-login-header'>
          <Text className='store-login-title'>门店管理登录</Text>
          <Text className='store-login-subtitle'>请输入门店账号和密码</Text>
        </View>

        <View className='store-login-form'>
          <View className='store-login-field'>
            <Text className='store-login-field__icon'>📱</Text>
            <Input
              className='store-login-field__input'
              type='text'
              placeholder='请输入手机号'
              maxlength={11}
              value={phone}
              onInput={(e) => setPhone(e.detail.value)}
            />
          </View>
          <View className='store-login-field'>
            <Text className='store-login-field__icon'>🔒</Text>
            <Input
              className='store-login-field__input'
              type='text'
              password
              placeholder='请输入密码'
              value={password}
              onInput={(e) => setPassword(e.detail.value)}
            />
          </View>

          <View
            className={`store-login-btn ${loading ? 'store-login-btn--loading' : ''}`}
            onClick={handleLogin}
          >
            <Text className='store-login-btn__text'>
              {loading ? '登录中...' : '登录'}
            </Text>
          </View>
        </View>

        <View className='store-login-footer'>
          <Text className='store-login-footer__text'>
            门店账号由管理员创建，如需账号请联系管理员
          </Text>
        </View>
      </View>
    </View>
  )
}

export default StoreLogin
