import React, { useEffect, useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet, Switch, TouchableOpacity, } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { DateTimePickerAndroid, DateTimePickerEvent } from '@react-native-community/datetimepicker';
import { useSelector } from 'react-redux';

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

export default function CategoryScreen() {
    const colorScheme = useColorScheme() ?? 'light';
    const navigation = useNavigation();
    const { token } = useToken();
    const session = useSelector( (state: any) => state.data.session );

    const [ sessionSet, setSessionSet ] = useState( false );

    const [ isDayBeforeEnabled, setIsDayBeforeEnabled ] = useState( true );
    const [ dayBefore, setDayBefore ] = useState( '19:30' );

    const [ isSameDayEnabled, setIsSameDayEnabled ] = useState( false );
    const [ sameDay, setSameDay ] = useState( '08:00' );

    let currentEdit = '';

    // Set page title
    useEffect( () => {
        // Set page title
        navigation.setOptions( { title: ( 'Notificaties' ) } );
    }, [] );

    // Set session data
    useEffect( () => {
        if (!sessionSet) {
            if (session.notifications.dayBefore === 'off') {
                setIsDayBeforeEnabled( false );
            } else {
                setIsDayBeforeEnabled( true );
                setDayBefore( session.notifications.dayBefore );
            }

            if (session.notifications.sameDay === 'off') {
                setIsSameDayEnabled( false );
            } else {
                setIsSameDayEnabled( true );
                setSameDay( session.notifications.sameDay );
            }
        }

        setSessionSet( true );
    }, [ session ] );

    // Update session when something changes
    useEffect( () => {
        updateSession();
    }, [ isSameDayEnabled, sameDay, isDayBeforeEnabled, dayBefore ] );

    // Open time picker
    const selectTime = (type: string) => {
        currentEdit = type;

        let time;
        if (type === 'dayBefore') {
            time = new Date( `1970-01-01T${dayBefore}` );
        } else {
            time = new Date( `1970-01-01T${sameDay}` );
        }

        if (time) {
            DateTimePickerAndroid.open( {
                value: time,
                onChange,
                mode: 'time',
                is24Hour: true,
                positiveButton: { label: 'Kies' },
                negativeButton: { label: 'Sluiten' },
            } );
        }
    }

    // Set selected time
    const onChange = (event: DateTimePickerEvent, selectedDate?: Date) => {
        if (selectedDate) {
            // Format to time string
            const hours = selectedDate.getHours().toString().padStart( 2, '0' );
            const minutes = selectedDate.getMinutes().toString().padStart( 2, '0' );
            const timeString = `${hours}:${minutes}`;

            if (currentEdit === 'dayBefore') {
                const minDate = new Date( `1970-01-01T16:00` );
                if (minDate > selectedDate) {
                    Message.error( 'Meldingen voor 16:00 worden niet ondersteund' );

                    return;
                }
            } else {
                const minDate = new Date( `1970-01-01T09:00` );
                if (minDate < selectedDate) {
                    Message.error( 'Meldingen na 09:00 worden niet ondersteund' );

                    return;
                }
            }

            if (currentEdit === 'dayBefore') {
                setDayBefore( timeString );
            } else {
                setSameDay( timeString )
            }
        }
    };

    const toggleDate = (type: string) => {
        if (type === 'dayBefore') {
            setIsDayBeforeEnabled( !isDayBeforeEnabled )
        } else {
            setIsSameDayEnabled( !isSameDayEnabled )
        }
    }

    const updateSession = () => {
        if (!sessionSet) {
            return;
        }

        const postData = {
            token: token,
            notification_day_before: isDayBeforeEnabled ? dayBefore : 'off',
            notification_same_day: isSameDayEnabled ? sameDay : 'off',
        };

        Request.post( 'sessions/update', postData ).then( (response) => {
            if (response.success) {
                store.dispatch( setSession( response.session ) );
            } else {
                Message.error( 'Er ging iets mis. Probeer het later opnieuw.' );
            }
        } )
    }

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: Colors[ colorScheme ].background }}>
            <ScrollView style={styles.container}>
                <ThemedView style={styles.listContainer}>
                    <ThemedView style={styles.listItem}>
                        <ThemedView style={styles.listTitle}>
                            <Switch
                                trackColor={{ false: '#767577', true: Colors[ colorScheme ].tint }}
                                thumbColor={'#fff'}
                                value={isDayBeforeEnabled}
                                style={styles.listSwitch}
                                onValueChange={() => toggleDate( 'dayBefore' )}
                            />
                            <ThemedText type="defaultSemiBold">Dag van te voren</ThemedText>
                        </ThemedView>

                        {isDayBeforeEnabled ?
                            (
                                <TouchableOpacity style={styles.listEdit} onPress={() => selectTime( 'dayBefore' )}>
                                    <ThemedText style={styles.listEditText}>Om {dayBefore}</ThemedText>
                                    <ThemedIcon size={18} name="chevron-forward" style={styles.listEditIcon}/>
                                </TouchableOpacity>
                            ) :
                            (
                                <ThemedText style={styles.listEdit}>
                                    <ThemedText style={styles.listEditText}>Uit</ThemedText>
                                </ThemedText>
                            )
                        }


                    </ThemedView>

                    <ThemedView style={styles.listItem}>
                        <ThemedView style={styles.listTitle}>
                            <Switch
                                trackColor={{ false: '#767577', true: Colors[ colorScheme ].tint }}
                                thumbColor={'#fff'}
                                value={isSameDayEnabled}
                                style={styles.listSwitch}
                                onValueChange={() => toggleDate( 'sameDay' )}
                            />
                            <ThemedText type="defaultSemiBold">Op de ophaaldag</ThemedText>
                        </ThemedView>

                        {isSameDayEnabled ?
                            (
                                <TouchableOpacity style={styles.listEdit} onPress={() => selectTime( 'sameDay' )}>
                                    <ThemedText style={styles.listEditText}>Om {sameDay}</ThemedText>
                                    <ThemedIcon size={18} name="chevron-forward" style={styles.listEditIcon}/>
                                </TouchableOpacity>
                            ) :
                            (
                                <ThemedView style={styles.listEdit}>
                                    <ThemedText style={styles.listEditText}>Uit</ThemedText>
                                </ThemedView>
                            )
                        }

                    </ThemedView>
                </ThemedView>
            </ScrollView>
        </SafeAreaView>
    );
}

const styles = StyleSheet.create( {
    container: {
        padding: 25,
    },
    htmlContainer: {
        paddingBottom: 50,
    },
    listContainer: {
        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',
    },
    listSwitch: {
        marginRight: 5,
    },
    listEdit: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        textAlign: 'right',
    },
    listEditText: {
        fontWeight: '300',
    },
    listEditIcon: {
        marginLeft: 10,
    },
} )