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="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      {user ? (
        <View className="p-6">
          <View className="bg-white rounded-2xl shadow-lg p-6 mb-6">
            <View className="flex items-center mb-6">
              <View className="w-20 h-20 rounded-full overflow-hidden mr-4">
                <Image
                  className="w-full h-full"
                  src={user.avatar || 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=160&h=160&fit=crop&crop=face'}
                />
              </View>
              <View>
                <Text className="text-gray-600 text-sm">欢迎回来</Text>
                <Text className="text-2xl font-bold text-gray-900">{user.username}</Text>
              </View>
            </View>
            
            <View className="space-y-4 mb-6">
              <View className="flex justify-between items-center py-3 border-b border-gray-100">
                <Text className="text-gray-600">用户ID</Text>
                <Text className="text-gray-900 font-mono">{user.id}</Text>
              </View>
              {user.email && (
                <View className="flex justify-between items-center py-3 border-b border-gray-100">
                  <Text className="text-gray-600">邮箱</Text>
                  <Text className="text-gray-900">{user.email}</Text>
                </View>
              )}
              <View className="flex justify-between items-center py-3">
                <Text className="text-gray-600">注册时间</Text>
                <Text className="text-gray-900">{new Date(user.createdAt).toLocaleDateString()}</Text>
              </View>
            </View>
            
            <View className="flex space-x-3">
              <Button className="flex-1" type="primary" onClick={handleProfile}>
                查看资料
              </Button>
              <Button
                className="flex-1"
                loading={loading}
                onClick={handleLogout}
              >
                退出登录
              </Button>
            </View>
          </View>
          
          <View className="grid grid-cols-3 gap-4">
            <View className="bg-white rounded-xl shadow-lg p-4 text-center">
              <Text className="text-3xl font-bold text-blue-600 mb-1">1</Text>
              <Text className="text-gray-600 text-sm">今日访问</Text>
            </View>
            <View className="bg-white rounded-xl shadow-lg p-4 text-center">
              <Text className="text-3xl font-bold text-green-600 mb-1">7</Text>
              <Text className="text-gray-600 text-sm">本周活跃</Text>
            </View>
            <View className="bg-white rounded-xl shadow-lg p-4 text-center">
              <Text className="text-3xl font-bold text-purple-600 mb-1">30</Text>
              <Text className="text-gray-600 text-sm">本月使用</Text>
            </View>
          </View>
        </View>
      ) : (
        <View className="p-6">
          <View className="flex flex-col items-center mb-8">
            <Image
              className="w-32 h-32 rounded-full mx-auto mb-4"
              src="https://images.unsplash.com/photo-1551650975-87deedd944c3?w=192&h=192&fit=crop"
            />
            <Text className="text-3xl font-bold text-gray-900 mb-2">欢迎使用小程序</Text>
            <Text className="text-gray-600 text-lg">请先登录以使用完整功能</Text>
          </View>
          
          <View className="bg-white rounded-2xl shadow-lg p-6 mb-6">
            <View className="space-y-4">
              <Button
                className="w-full"
                type="primary"
                onClick={handleLogin}
              >
                立即登录
              </Button>
              <Button
                className="w-full"
                plain
                onClick={goToRegister}
              >
                注册新账号
              </Button>
            </View>
          </View>
          
          <View>
            <Text className="text-xl font-bold text-gray-900 mb-4 block">功能特色</Text>
            <View className="grid grid-cols-2 gap-4">
              <View className="bg-white rounded-xl shadow-lg p-4">
                <View className="text-2xl mb-2">
                  <View className="i-heroicons-lock-closed-16-solid" />
                </View>
                <Text className="font-bold text-gray-900 mb-1 block">安全认证</Text>
                <Text className="text-gray-600 text-sm">多重加密保护账户安全</Text>
              </View>
              <View className="bg-white rounded-xl shadow-lg p-4">
                <View className="text-2xl mb-2">👤</View>
                <Text className="font-bold text-gray-900 mb-1 block">用户管理</Text>
                <Text className="text-gray-600 text-sm">完整的用户信息管理</Text>
              </View>
              <View className="bg-white rounded-xl shadow-lg p-4">
                <View className="text-2xl mb-2">📱</View>
                <Text className="font-bold text-gray-900 mb-1 block">响应式设计</Text>
                <Text className="text-gray-600 text-sm">完美适配各种设备</Text>
              </View>
              <View className="bg-white rounded-xl shadow-lg p-4">
                <View className="text-2xl mb-2">⚡</View>
                <Text className="font-bold text-gray-900 mb-1 block">实时同步</Text>
                <Text className="text-gray-600 text-sm">数据实时更新同步</Text>
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}
