// screens/RegistrationScreen.js
import React, { useState, useContext } from 'react';
import {
    StyleSheet,
    ScrollView,
    Alert,
    KeyboardAvoidingView,
    Platform,
    View,
} from 'react-native';
import axios from 'axios';
import { Picker } from '@react-native-picker/picker';
import MultiSelect from 'react-native-multiple-select';
import { AuthContext } from '../context/AuthContext';
import {
    Text,
    TextInput,
    Button,
    Card,
    HelperText,
    ActivityIndicator,
    useTheme,
} from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';

const RegistrationScreen = ({ navigation }) => {
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [desiredPhysique, setDesiredPhysique] = useState('lean');
    const [fitnessGoals, setFitnessGoals] = useState([]);
    const [dietaryPreferences, setDietaryPreferences] = useState([]);
    const [dietaryRestrictions, setDietaryRestrictions] = useState([]);
    const [loading, setLoading] = useState(false);

    const { signIn } = useContext(AuthContext);

    const theme = useTheme();

    // Sample options for multi-select fields
    const fitnessGoalsOptions = [
        { id: 'strength', name: 'Strength' },
        { id: 'endurance', name: 'Endurance' },
        { id: 'flexibility', name: 'Flexibility' },
        { id: 'weight_loss', name: 'Weight Loss' },
        { id: 'muscle_gain', name: 'Muscle Gain' },
    ];

    const dietaryPreferencesOptions = [
        { id: 'vegetarian', name: 'Vegetarian' },
        { id: 'vegan', name: 'Vegan' },
        { id: 'keto', name: 'Keto' },
        { id: 'paleo', name: 'Paleo' },
        { id: 'mediterranean', name: 'Mediterranean' },
    ];

    const dietaryRestrictionsOptions = [
        { id: 'gluten_free', name: 'Gluten-Free' },
        { id: 'dairy_free', name: 'Dairy-Free' },
        { id: 'nut_allergy', name: 'Nut Allergy' },
        { id: 'lactose_intolerant', name: 'Lactose Intolerant' },
        { id: 'none', name: 'None' },
    ];

    const handleRegistration = async () => {
        // Basic validation
        if (!username || !email || !password || !desiredPhysique) {
            Alert.alert('Error', 'Please fill in all required fields.');
            return;
        }

        setLoading(true);

        try {
            const response = await axios.post('http://10.0.0.203:5000/api/auth/register', {
                username,
                email,
                password,
                desiredPhysique,
                fitnessGoals,
                dietaryPreferences,
                dietaryRestrictions,
            });

            if (response.status === 201) {
                const { token } = response.data;
                Alert.alert('Success', 'Registration successful!', [
                    { text: 'OK', onPress: () => navigation.navigate('Login') },
                ]);
                signIn(token);
            }
        } catch (error) {
            console.error('Registration Error:', error);
            console.error('Backend URL:', '10.0.0.203:5000');
            if (error.response) {
                console.error('Error Response:', error.response.data);
                Alert.alert('Registration Failed', error.response.data.error || error.response.data.message);
            } else if (error.request) {
                console.error('No Response:', error.request);
                Alert.alert('Registration Failed', 'No response from server. Please try again.');
            } else {
                console.error('Error Setting Up Request:', error.message);
                Alert.alert('Registration Failed', error.message);
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
            style={styles.container}
        >
            <ScrollView contentContainerStyle={styles.scrollContainer}>
                <Card style={styles.card}>
                    <Card.Title
                        title="Create Account"
                        titleStyle={styles.cardTitle}
                        left={(props) => <Icon {...props} name="account-plus" size={30} color={theme.colors.primary} />}
                    />
                    <Card.Content>
                        <TextInput
                            label="Username"
                            value={username}
                            onChangeText={setUsername}
                            mode="outlined"
                            style={styles.input}
                            autoCapitalize="none"
                            left={<TextInput.Icon name="account" color={theme.colors.placeholder} />}
                            placeholderTextColor={theme.colors.placeholder}
                        />
                        <TextInput
                            label="Email"
                            value={email}
                            onChangeText={setEmail}
                            mode="outlined"
                            style={styles.input}
                            keyboardType="email-address"
                            autoCapitalize="none"
                            left={<TextInput.Icon name="email" color={theme.colors.placeholder} />}
                            placeholderTextColor={theme.colors.placeholder}
                        />
                        <TextInput
                            label="Password"
                            value={password}
                            onChangeText={setPassword}
                            mode="outlined"
                            style={styles.input}
                            secureTextEntry
                            left={<TextInput.Icon name="lock" color={theme.colors.placeholder} />}
                            placeholderTextColor={theme.colors.placeholder}
                        />

                        <Text style={styles.label}>Desired Physique</Text>
                        <View style={[styles.pickerContainer, { borderColor: theme.colors.placeholder }]}>
                            <Picker
                                selectedValue={desiredPhysique}
                                onValueChange={(itemValue) => setDesiredPhysique(itemValue)}
                                style={[styles.picker, { color: theme.colors.text }]}
                                dropdownIconColor={theme.colors.placeholder}
                                mode="dropdown"
                            >
                                <Picker.Item label="Lean" value="lean" />
                                <Picker.Item label="Muscular" value="muscular" />
                                <Picker.Item label="Athletic" value="athletic" />
                            </Picker>
                        </View>

                        <Text style={styles.label}>Fitness Goals</Text>
                        <MultiSelect
                            items={fitnessGoalsOptions}
                            uniqueKey="id"
                            onSelectedItemsChange={setFitnessGoals}
                            selectedItems={fitnessGoals}
                            selectText="Select Fitness Goals"
                            searchInputPlaceholderText="Search Goals..."
                            tagRemoveIconColor={theme.colors.accent}
                            tagBorderColor={theme.colors.accent}
                            tagTextColor={theme.colors.text}
                            selectedItemTextColor={theme.colors.primary}
                            selectedItemIconColor={theme.colors.primary}
                            itemTextColor={theme.colors.text}
                            displayKey="name"
                            searchInputStyle={{ color: theme.colors.text }}
                            submitButtonColor={theme.colors.primary}
                            submitButtonText="Submit"
                            styleMainWrapper={styles.multiSelectWrapper}
                            styleDropdownMenuSubsection={styles.multiSelectDropdown}
                            fontFamily="System"
                        />

                        <Text style={styles.label}>Dietary Preferences</Text>
                        <MultiSelect
                            items={dietaryPreferencesOptions}
                            uniqueKey="id"
                            onSelectedItemsChange={setDietaryPreferences}
                            selectedItems={dietaryPreferences}
                            selectText="Select Dietary Preferences"
                            searchInputPlaceholderText="Search Preferences..."
                            tagRemoveIconColor={theme.colors.accent}
                            tagBorderColor={theme.colors.accent}
                            tagTextColor={theme.colors.text}
                            selectedItemTextColor={theme.colors.primary}
                            selectedItemIconColor={theme.colors.primary}
                            itemTextColor={theme.colors.text}
                            displayKey="name"
                            searchInputStyle={{ color: theme.colors.text }}
                            submitButtonColor={theme.colors.primary}
                            submitButtonText="Submit"
                            styleMainWrapper={styles.multiSelectWrapper}
                            styleDropdownMenuSubsection={styles.multiSelectDropdown}
                            fontFamily="System"
                        />

                        <Text style={styles.label}>Dietary Restrictions</Text>
                        <MultiSelect
                            items={dietaryRestrictionsOptions}
                            uniqueKey="id"
                            onSelectedItemsChange={setDietaryRestrictions}
                            selectedItems={dietaryRestrictions}
                            selectText="Select Dietary Restrictions"
                            searchInputPlaceholderText="Search Restrictions..."
                            tagRemoveIconColor={theme.colors.accent}
                            tagBorderColor={theme.colors.accent}
                            tagTextColor={theme.colors.text}
                            selectedItemTextColor={theme.colors.primary}
                            selectedItemIconColor={theme.colors.primary}
                            itemTextColor={theme.colors.text}
                            displayKey="name"
                            searchInputStyle={{ color: theme.colors.text }}
                            submitButtonColor={theme.colors.primary}
                            submitButtonText="Submit"
                            styleMainWrapper={styles.multiSelectWrapper}
                            styleDropdownMenuSubsection={styles.multiSelectDropdown}
                            fontFamily="System"
                        />

                        {loading ? (
                            <ActivityIndicator animating={true} color={theme.colors.primary} style={styles.loader} />
                        ) : (
                            <Button
                                mode="contained"
                                onPress={handleRegistration}
                                style={styles.button}
                                contentStyle={styles.buttonContent}
                                disabled={loading}
                            >
                                Register
                            </Button>
                        )}

                        <View style={styles.loginRedirect}>
                            <Text style={styles.redirectText}>Already have an account?</Text>
                            <Button
                                mode="text"
                                onPress={() => navigation.navigate('Login')}
                                compact
                                uppercase={false}
                                labelStyle={styles.redirectButtonText}
                            >
                                Login
                            </Button>
                        </View>
                    </Card.Content>
                </Card>
            </ScrollView>
        </KeyboardAvoidingView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#121212', // Dark background
    },
    scrollContainer: {
        flexGrow: 1,
        justifyContent: 'center',
        padding: 20,
    },
    card: {
        backgroundColor: '#1e1e1e',
        borderRadius: 10,
        padding: 10,
        elevation: 5,
    },
    cardTitle: {
        color: '#ffffff',
        fontSize: 24,
        fontWeight: 'bold',
    },
    input: {
        backgroundColor: '#2c2c2c',
        marginBottom: 10,
    },
    label: {
        fontSize: 16,
        color: '#ffffff',
        marginTop: 10,
        marginBottom: 5,
    },
    pickerContainer: {
        borderRadius: 5,
        borderWidth: 1,
        backgroundColor: '#2c2c2c',
        marginBottom: 15,
        overflow: 'hidden',
    },
    picker: {
        height: 50,
        width: '100%',
    },
    multiSelectWrapper: {
        marginBottom: 15,
    },
    multiSelectDropdown: {
        borderRadius: 5,
        backgroundColor: '#2c2c2c',
    },
    button: {
        marginTop: 10,
        borderRadius: 25,
    },
    buttonContent: {
        paddingVertical: 8,
    },
    loginRedirect: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 20,
    },
    redirectText: {
        color: '#ffffff',
    },
    redirectButtonText: {
        color: '#03dac6',
        fontWeight: '600',
    },
    loader: {
        marginTop: 10,
    },
});

export default RegistrationScreen;

 ERROR  VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because it can break windowing and other functionality - use another VirtualizedList-backed container instead.