import React, { useState } from 'react';
import {
    View,
    Text,
    StyleSheet,
    TextInput,
    TouchableOpacity,
    KeyboardAvoidingView,
    Platform,
    SafeAreaView,
    ScrollView,
    Alert,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Feather, MaterialCommunityIcons } from '@expo/vector-icons';
import { colors, spacing, borderRadius, typography, shadows } from '../theme/colors';
import { useAuth } from '../context/AuthContext';
import { ActivityIndicator } from 'react-native';

export default function RegisterScreen({ navigation }: any) {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [error, setError] = useState<string | null>(null);
    const { signUp, isLoading } = useAuth();

    const handleRegister = async () => {
        setError(null);
        if (!name || !email || !password || !confirmPassword) {
            setError('Please fill in all fields.');
            return;
        }

        if (password !== confirmPassword) {
            setError('Passwords do not match.');
            return;
        }

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            setError('Please enter a valid email address.');
            return;
        }

        try {
            await signUp({ username: name, email, password });
        } catch (err: any) {
            setError(err.message || 'Registration failed. Please try again.');
        }
    };

    return (
        <View style={styles.container}>
            <LinearGradient
                colors={[colors.sentinel.backgroundGradientStart, colors.sentinel.backgroundGradientEnd]}
                style={styles.gradient}
            >
                <SafeAreaView style={styles.safeArea}>
                    <KeyboardAvoidingView
                        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                        style={styles.content}
                    >
                        <ScrollView
                            showsVerticalScrollIndicator={false}
                            contentContainerStyle={styles.scrollContent}
                        >
                            <TouchableOpacity
                                style={styles.backButton}
                                onPress={() => navigation.goBack()}
                            >
                                <Feather name="arrow-left" size={24} color={colors.sentinel.text} />
                            </TouchableOpacity>

                            <View style={styles.header}>
                                <View style={styles.logoContainer}>
                                    <MaterialCommunityIcons name="compass-outline" size={48} color={colors.sentinel.primary} />
                                </View>
                                <Text style={styles.title}>Join the Fleet</Text>
                                <Text style={styles.subtitle}>Begin your journey with Sentinel</Text>
                                {error && (
                                    <View style={styles.errorContainer}>
                                        <MaterialCommunityIcons name="alert-circle-outline" size={20} color={colors.sentinel.statusCritical} />
                                        <Text style={styles.errorText}>{error}</Text>
                                    </View>
                                )}
                            </View>

                            <View style={styles.form}>
                                <View style={styles.inputContainer}>
                                    <Feather name="user" size={20} color={colors.sentinel.textSecondary} style={styles.inputIcon} />
                                    <TextInput
                                        style={styles.input}
                                        placeholder="Captain's Name"
                                        placeholderTextColor={colors.sentinel.textSecondary}
                                        value={name}
                                        onChangeText={setName}
                                    />
                                </View>

                                <View style={styles.inputContainer}>
                                    <Feather name="mail" size={20} color={colors.sentinel.textSecondary} style={styles.inputIcon} />
                                    <TextInput
                                        style={styles.input}
                                        placeholder="Email"
                                        placeholderTextColor={colors.sentinel.textSecondary}
                                        value={email}
                                        onChangeText={setEmail}
                                        autoCapitalize="none"
                                        keyboardType="email-address"
                                    />
                                </View>

                                <View style={styles.inputContainer}>
                                    <Feather name="lock" size={20} color={colors.sentinel.textSecondary} style={styles.inputIcon} />
                                    <TextInput
                                        style={styles.input}
                                        placeholder="Password"
                                        placeholderTextColor={colors.sentinel.textSecondary}
                                        value={password}
                                        onChangeText={setPassword}
                                        secureTextEntry
                                    />
                                </View>

                                <View style={styles.inputContainer}>
                                    <Feather name="check-circle" size={20} color={colors.sentinel.textSecondary} style={styles.inputIcon} />
                                    <TextInput
                                        style={styles.input}
                                        placeholder="Confirm Password"
                                        placeholderTextColor={colors.sentinel.textSecondary}
                                        value={confirmPassword}
                                        onChangeText={setConfirmPassword}
                                        secureTextEntry
                                    />
                                </View>

                                <TouchableOpacity
                                    style={[styles.registerButton, isLoading && styles.disabledButton]}
                                    activeOpacity={0.8}
                                    onPress={handleRegister}
                                    disabled={isLoading}
                                >
                                    {isLoading ? (
                                        <ActivityIndicator color={colors.white} />
                                    ) : (
                                        <Text style={styles.registerButtonText}>Create Account</Text>
                                    )}
                                </TouchableOpacity>

                                <TouchableOpacity
                                    style={styles.loginLink}
                                    onPress={() => navigation.navigate('Login')}
                                >
                                    <Text style={styles.loginLinkText}>
                                        Already have an account? <Text style={styles.highlight}>Login</Text>
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        </ScrollView>
                    </KeyboardAvoidingView>
                </SafeAreaView>
            </LinearGradient>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    gradient: {
        flex: 1,
    },
    safeArea: {
        flex: 1,
    },
    content: {
        flex: 1,
    },
    scrollContent: {
        flexGrow: 1,
        paddingHorizontal: spacing.lg,
        paddingBottom: spacing.xl,
    },
    backButton: {
        marginTop: spacing.md,
        marginBottom: spacing.lg,
        width: 40,
        height: 40,
        borderRadius: borderRadius.full,
        backgroundColor: 'rgba(255, 255, 255, 0.05)',
        alignItems: 'center',
        justifyContent: 'center',
    },
    header: {
        alignItems: 'center',
        marginBottom: spacing.xl,
    },
    logoContainer: {
        width: 80,
        height: 80,
        borderRadius: borderRadius.full,
        backgroundColor: 'rgba(255, 255, 255, 0.1)',
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: spacing.lg,
        borderWidth: 1,
        borderColor: 'rgba(184, 224, 229, 0.2)',
    },
    title: {
        fontSize: typography.fontSize.xxl,
        fontWeight: 'bold',
        color: colors.sentinel.text,
        marginBottom: spacing.xs,
        letterSpacing: 0.5,
    },
    subtitle: {
        fontSize: typography.fontSize.base,
        color: colors.sentinel.textSecondary,
    },
    form: {
        width: '100%',
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'rgba(255, 255, 255, 0.05)',
        borderRadius: borderRadius.lg,
        borderWidth: 1,
        borderColor: 'rgba(184, 224, 229, 0.1)',
        marginBottom: spacing.base,
        height: 56,
        paddingHorizontal: spacing.base,
    },
    inputIcon: {
        marginRight: spacing.md,
    },
    input: {
        flex: 1,
        color: colors.sentinel.text,
        fontSize: typography.fontSize.base,
    },
    registerButton: {
        backgroundColor: colors.nautical.seafoam,
        height: 56,
        borderRadius: borderRadius.lg,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: spacing.md,
        ...shadows.glow,
    },
    registerButtonText: {
        color: colors.white,
        fontSize: typography.fontSize.md,
        fontWeight: 'bold',
        letterSpacing: 0.5,
    },
    loginLink: {
        alignItems: 'center',
        marginTop: spacing.xl,
    },
    loginLinkText: {
        color: colors.sentinel.textSecondary,
        fontSize: typography.fontSize.base,
    },
    highlight: {
        color: colors.nautical.seafoam,
        fontWeight: 'bold',
    },
    disabledButton: {
        opacity: 0.7,
    },
    errorContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'rgba(255, 68, 68, 0.1)',
        padding: spacing.sm,
        borderRadius: borderRadius.md,
        marginTop: spacing.md,
        borderWidth: 1,
        borderColor: 'rgba(255, 68, 68, 0.2)',
    },
    errorText: {
        color: colors.sentinel.statusCritical,
        fontSize: typography.fontSize.sm,
        marginLeft: spacing.xs,
        fontWeight: '500',
    },
});
