import {SegmentedControl, View} from "react-native-ui-lib";
import React, {memo, useCallback, useMemo, useRef, useEffect} from "react";
import {StyleSheet} from "react-native";
import {NavigationProp, useNavigationState} from "@react-navigation/native";

interface ViewSwitchProps {
    navigation: NavigationProp<any>;
}

const ViewSwitch = memo(function ViewSwitch({navigation}: ViewSwitchProps) {
    const currentIndex = useNavigationState((state) => state.index === 6 ? 1 : 0);
    const isInitialMount = useRef(true);
    const navigationPending = useRef(false);

    useEffect(() => {
        if (isInitialMount.current) {
            isInitialMount.current = false;
            return;
        }
    }, []);

    const handleSegmentChange = useCallback(
        (index: number) => {
            if (navigationPending.current) return;

            navigationPending.current = true;
            setTimeout(() => {
                navigation.navigate(index === 0 ? "calendar" : "todos");
                navigationPending.current = false;
            }, 300);
        },
        [navigation]
    );

    const segments = useMemo(() => [
        {label: "Calendar", segmentLabelStyle: styles.labelStyle},
        {label: "To Dos", segmentLabelStyle: styles.labelStyle},
    ], []);

    return (
        <View style={styles.container}>
            <SegmentedControl
                segments={segments}
                containerStyle={styles.segmentContainer}
                style={styles.segment}
                backgroundColor="#ebebeb"
                inactiveColor="black"
                activeColor="white"
                activeBackgroundColor="#ea156c"
                outlineColor="white"
                outlineWidth={3}
                onChangeIndex={handleSegmentChange}
                initialIndex={currentIndex}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        borderRadius: 30,
        backgroundColor: "#ebebeb",
        shadowColor: "#000",
        shadowOffset: {width: 0, height: 0},
        shadowOpacity: 0,
        shadowRadius: 0,
        elevation: 0,
    },
    segmentContainer: {
        height: 44,
        width: 220,
    },
    segment: {
        borderRadius: 50,
        borderWidth: 0,
        height: 44,
    },
    labelStyle: {
        fontSize: 16,
        fontFamily: "Manrope_600SemiBold",
    },
});

export default ViewSwitch;
