import React, { useEffect } from 'react'
import { View, StyleSheet, StatusBar as RNStatusBar } from 'react-native'
import { StatusBar } from 'expo-status-bar'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRouter } from 'expo-router'
import { LinearGradient } from 'expo-linear-gradient'
import { AuthForm } from '@/components/blocks/AuthForm'
import { useSession } from '@/lib/auth'

export default function Auth() {
    const router = useRouter()
    const { data: session, isPending } = useSession()

    useEffect(() => {
        // 如果用户已登录，跳转到首页
        if (session?.user) {
            router.replace('/(tabs)' as any)
        }
    }, [session, router])

    // 会话加载中显示空白
    if (isPending) {
        return (
            <View style={styles.container}>
                <StatusBar style="light" />
            </View>
        )
    }

    // 如果已登录，不显示内容（等待跳转）
    if (session?.user) {
        return null
    }

    const handleSuccess = () => {
        router.replace('/(tabs)' as any)
    }

    return (
        <LinearGradient
            colors={['#1a1a2e', '#16213e', '#0f3460']}
            locations={[0, 0.5, 1]}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.background}
        >
            <SafeAreaView style={styles.container} edges={['top']}>
                <StatusBar style="light" />
                <RNStatusBar barStyle="light-content" />

                <View style={styles.content}>
                    <AuthForm onSuccess={handleSuccess} />
                </View>
            </SafeAreaView>
        </LinearGradient>
    )
}

const styles = StyleSheet.create({
    background: {
        flex: 1,
        width: '100%',
        height: '100%',
    },
    container: {
        flex: 1,
        backgroundColor: 'transparent',
    },
    content: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 20,
    },
})
