import { View, Text, Button, Image } from '@tarojs/components'
import { useLoad, useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import Taro from '@tarojs/taro'
import { authManager, User } from '../../utils/auth'
import './index.css'

export default function Index() {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(false)

  useLoad(() => {
    console.log('Index Page loaded.')
    checkLoginStatus()
  })

  useDidShow(() => {
    checkLoginStatus()
  })

  const checkLoginStatus = async () => {
    if (authManager.isLoggedIn()) {
      const userInfo = authManager.getUserInfo()
      setUser(userInfo)
    } else {
      setUser(null)
    }
  }

  const handleLogin = () => {
    Taro.navigateTo({ url: '/pages/login/index' })
  }

  const handleLogout = async () => {
    setLoading(true)
    try {
      await authManager.logout()
      setUser(null)
      Taro.showToast({
        title: '退出成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleProfile = () => {
    Taro.navigateTo({ url: '/pages/profile/index' })
  }

  const goToRegister = () => {
    Taro.navigateTo({ url: '/pages/register/index' })
  }

  return (
    <View className="index-container">
      {user ? (
        <View className="user-welcome">
          <View className="user-card">
            <View className="user-header">
              <View className="user-avatar">
                <Image
                  className="avatar-image"
                  src={user.avatar || 'https://via.placeholder.com/160x160'}
                  mode="aspectFill"
                />
              </View>
              <View className="user-greeting">
                <Text className="welcome-text">欢迎回来</Text>
                <Text className="username">{user.username}</Text>
              </View>
            </View>
            
            <View className="user-info">
              <View className="info-item">
                <Text className="info-label">用户ID</Text>
                <Text className="info-value">{user.id}</Text>
              </View>
              {user.email && (
                <View className="info-item">
                  <Text className="info-label">邮箱</Text>
                  <Text className="info-value">{user.email}</Text>
                </View>
              )}
              <View className="info-item">
                <Text className="info-label">注册时间</Text>
                <Text className="info-value">{new Date(user.createdAt).toLocaleDateString()}</Text>
              </View>
            </View>
            
            <View className="action-buttons">
              <Button className="action-button primary" type="primary" onClick={handleProfile}>
                查看资料
              </Button>
              <Button
                className="action-button secondary"
                loading={loading}
                onClick={handleLogout}
              >
                退出登录
              </Button>
            </View>
          </View>
          
          <View className="stats-section">
            <View className="stat-card">
              <Text className="stat-number">1</Text>
              <Text className="stat-label">今日访问</Text>
            </View>
            <View className="stat-card">
              <Text className="stat-number">7</Text>
              <Text className="stat-label">本周活跃</Text>
            </View>
            <View className="stat-card">
              <Text className="stat-number">30</Text>
              <Text className="stat-label">本月使用</Text>
            </View>
          </View>
        </View>
      ) : (
        <View className="login-prompt">
          <View className="welcome-header">
            <Image
              className="welcome-icon"
              src="https://via.placeholder.com/192x192/1890ff/ffffff?text=LOGO"
              mode="aspectFit"
            />
            <Text className="welcome-title">欢迎使用小程序</Text>
            <Text className="welcome-subtitle">请先登录以使用完整功能</Text>
          </View>
          
          <View className="login-card">
            <View className="login-buttons">
              <Button
                className="login-button primary"
                type="primary"
                onClick={handleLogin}
              >
                立即登录
              </Button>
              <Button
                className="login-button secondary"
                plain
                onClick={goToRegister}
              >
                注册新账号
              </Button>
            </View>
          </View>
          
          <View className="features-section">
            <Text className="features-title">功能特色</Text>
            <View className="features-grid">
              <View className="feature-card">
                <View className="feature-icon">🔒</View>
                <Text className="feature-title">安全认证</Text>
                <Text className="feature-desc">多重加密保护账户安全</Text>
              </View>
              <View className="feature-card">
                <View className="feature-icon">👤</View>
                <Text className="feature-title">用户管理</Text>
                <Text className="feature-desc">完整的用户信息管理</Text>
              </View>
              <View className="feature-card">
                <View className="feature-icon">📱</View>
                <Text className="feature-title">响应式设计</Text>
                <Text className="feature-desc">完美适配各种设备</Text>
              </View>
              <View className="feature-card">
                <View className="feature-icon">⚡</View>
                <Text className="feature-title">实时同步</Text>
                <Text className="feature-desc">数据实时更新同步</Text>
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}
