import React, { useEffect, useState } from 'react';
import {
    StyleSheet,
    ScrollView,
    SafeAreaView,
    StatusBar,
    TouchableOpacity,
    Alert,
    TextInput,
} from 'react-native';
import { useRouter } from 'expo-router';
import Ionicons from '@expo/vector-icons/Ionicons';

import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { useToken } from '@/context/AppProvider';
import { Message } from '@/services/message';
import { Request } from '@/services/request';
import CustomModal from '@/components/EditModal';
import { err } from 'react-native-svg';

export default function SettingsScreen() {
    const colorScheme = useColorScheme() ?? 'light';
    const { token, isLoading } = useToken();
    const router = useRouter();

    // Name
    const [ name, setName ] = useState( '' );
    const [ nameModalVisible, setNameModalVisible ] = useState( false );

    // Address
    const [ zipcode, setZipcode ] = React.useState( '6715GA' );
    const [ houseNumber, setHouseNumber ] = React.useState( '3' );
    const [ street, setStreet ] = React.useState( '3' );
    const [ city, setCity ] = React.useState( '3' );
    const [ addressModalVisible, setAddressModalVisible ] = useState( false );

    useEffect( () => {
        // Load current session
        if (token) {
            Request.post( 'sessions/get', { token: token } ).then( (response) => {
                if (response.success) {
                    const { session } = response;

                    setSessionData( session );
                }
            } )
        }
    }, [] );

    // Set session data in view
    const setSessionData = (session: any) => {
        // Name
        setName( session.name )

        // Address
        setZipcode( session.address.zipcode );
        setHouseNumber( session.address.houseNumber );
        setStreet( session.address.street );
        setCity( session.address.city );
    }

    // Handle
    const handleSave = (inputValues: Record<string, string>) => {
        let postData: any = {token: token};

        if (inputValues.name) {
            postData[ 'name' ] = inputValues.name;
        }

        if (inputValues.zipcode) {
            postData[ 'zipcode' ] = inputValues.zipcode;
        }

        if (inputValues.houseNumber) {
            postData[ 'houseNumber' ] = inputValues.houseNumber;
        }

        Request.post( 'sessions/update', postData )
               .then( (response) => {
                   console.log('save', response);

                   if (response.success) {
                       setSessionData( response.session );

                       Message.success( 'Opgeslagen!' )
                   } else {
                       Message.error( response.message );
                   }
               } )
            .catch((error) => {
                console.log('error', error);
            })
    };

    const logout = () => {
        Alert.alert( 'Uitloggen', 'Weet je het zeker?', [
            {
                text: 'Annuleren',
                style: 'cancel',
            },
            {
                text: 'Ja',
                onPress: () => {
                    Request.post( 'sessions/delete' ).then( (response) => {
                        console.log( 'sessions delete', response );
                        if (!response.success) {
                            Message.success( 'Je bent uitgelogd' )

                            router.replace( '/(onboarding)/start' );
                        } else {
                            Message.error( 'Er is iets mis gegaan. Probeer het later opnieuw!' )
                        }
                    } )
                }
            },
        ] );
    }

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: Colors[ colorScheme ].background }}>
            <ThemedView style={styles.container}>
                <ScrollView>
                    <ThemedView style={styles.titleContainer}>
                        <ThemedText type="title">Instellingen</ThemedText>
                    </ThemedView>

                    <ThemedView style={styles.listContainer}>
                        <ThemedView style={styles.listItem}>
                            <ThemedView style={styles.listTitle}>
                                <Ionicons size={20} name="person-outline" style={styles.listIcon}/>
                                <ThemedText type="defaultSemiBold">Naam</ThemedText>
                            </ThemedView>

                            <TouchableOpacity style={styles.listEdit} onPress={() => setNameModalVisible( true )}>
                                <ThemedText style={styles.listEditText}>{name}</ThemedText>
                                <Ionicons size={18} name="chevron-forward" style={styles.listEditIcon}/>
                            </TouchableOpacity>
                        </ThemedView>

                        <ThemedView style={styles.listItem}>
                            <ThemedView style={styles.listTitle}>
                                <Ionicons size={20} name="trail-sign-outline" style={styles.listIcon}/>
                                <ThemedText type="defaultSemiBold">Adres</ThemedText>
                            </ThemedView>

                            <TouchableOpacity style={styles.listEdit} onPress={() => setAddressModalVisible( true )}>
                                <ThemedText style={styles.listEditText}>{street} {houseNumber}. {city}</ThemedText>
                                <Ionicons size={18} name="chevron-forward" style={styles.listEditIcon}/>
                            </TouchableOpacity>
                        </ThemedView>

                        <ThemedView style={styles.listItem}>
                            <ThemedView style={styles.listTitle}>
                                <Ionicons size={20} name="notifications-outline" style={styles.listIcon}/>
                                <ThemedText type="defaultSemiBold">Notificaties</ThemedText>
                            </ThemedView>

                            <TouchableOpacity style={styles.listEdit}>
                                <Ionicons size={18} name="chevron-forward" style={styles.listEditIcon}/>
                            </TouchableOpacity>
                        </ThemedView>
                    </ThemedView>

                    <ThemedText>
                        <TouchableOpacity onPress={logout}>
                            <ThemedText type="defaultSemiBold" style={styles.logout}>
                                Uitloggen
                            </ThemedText>
                        </TouchableOpacity>
                    </ThemedText>
                </ScrollView>
            </ThemedView>

            <CustomModal
                title="Naam wijzigen"
                visible={nameModalVisible}
                onClose={() => setNameModalVisible( false )}
                onSave={handleSave}
                fields={[
                    {
                        name: 'name',
                        placeholder: 'Je naam',
                        defaultValue: name,
                    },
                ]}
            />

            <CustomModal
                title="Adres wijzigen"
                visible={addressModalVisible}
                onClose={() => setAddressModalVisible( false )}
                onSave={handleSave}
                fields={[
                    {
                        name: 'zipcode',
                        title: 'Postcode',
                        placeholder: 'Je postcode',
                        defaultValue: zipcode,
                    },
                    {
                        name: 'houseNumber',
                        title: 'Huisnummer',
                        placeholder: 'Je huis nummer',
                        defaultValue: houseNumber,
                    },
                ]}
            />
        </SafeAreaView>
    );
}

const styles = StyleSheet.create( {
    container: {
        padding: 25,
        marginTop: StatusBar.currentHeight,
    },
    titleContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        gap: 8,
        paddingBottom: 8,
    },
    listContainer: {
        marginTop: 30,
        paddingBottom: 10
    },
    listItem: {
        flex: 1,
        display: 'flex',
        gap: 8,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingBottom: 20,
        marginBottom: 20,
        borderBottomWidth: 1,
        borderBottomColor: '#f2f2f2',
    },
    listIcon: {
        marginRight: 15,
    },
    listTitle: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
    },
    listEdit: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        textAlign: 'right',
    },
    listEditText: {
        fontWeight: '300',
    },
    listEditIcon: {
        marginLeft: 10,
    },
    logout: {
        color: Colors.red,
    },
} );
