import React, { useEffect, useState } from 'react';
import {
    StyleSheet,
    ScrollView,
    SafeAreaView,
    StatusBar,
    TouchableOpacity,
    Alert,
} from 'react-native';
import { useRouter } from 'expo-router';
import { useSelector } from 'react-redux';

import { ThemedText } from '@/lib/components/ThemedText';
import { ThemedView } from '@/lib/components/ThemedView';
import { Colors } from '@/lib/constants/Colors';
import { useColorScheme } from '@/lib/hooks/useColorScheme';
import { useToken } from '@/lib/context/AppProvider';
import { Message } from '@/lib/services/message';
import { Request } from '@/lib/services/request';
import CustomModal from '@/lib/components/EditModal';
import { store } from '@/lib/store/store';
import { setSession, setReloadCalendar } from '@/lib/store/dataStore';
import { ThemedIcon } from '@/lib/components/ThemedIcon';

export default function SettingsScreen() {
    const colorScheme = useColorScheme() ?? 'light';
    const { token, setToken } = useToken();
    const session = useSelector( (state: any) => state.data.session );
    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( () => {
        setSessionData( session );
    }, [ 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 save settings
    const handleSave = (inputValues: Record<string, string>) => {
        let postData: any = { token: token };

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

        let addressChanged = false;

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

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

        Request.post( 'sessions/update', postData )
               .then( (response) => {
                   if (response.success) {
                       setSessionData( response.session );

                       // Save to store
                       store.dispatch( setSession( response.session ) )
                       store.dispatch( setReloadCalendar( addressChanged ) )

                       Message.success( 'Opgeslagen!' )
                   } else {
                       Message.error( response.message );
                   }
               } );
    };

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

                            setToken( null );

                            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}>
                                <ThemedIcon name="person-outline" size={20} style={styles.listIcon}/>
                                <ThemedText type="defaultSemiBold">Naam</ThemedText>
                            </ThemedView>

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

                        <ThemedView style={styles.listItem}>
                            <ThemedView style={styles.listTitle}>
                                <ThemedIcon 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>
                                <ThemedIcon size={18} name="chevron-forward" style={styles.listEditIcon}/>
                            </TouchableOpacity>
                        </ThemedView>

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

                            <TouchableOpacity style={styles.listEdit} onPress={() => router.push( '/(settings)/notifications' )}>
                                <ThemedText style={styles.listEditText}>Wijzigen</ThemedText>
                                <ThemedIcon 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,
    },
} );
