trackActivityScreen

mail@pastecode.io avatar
unknown
plain_text
7 months ago
20 kB
1
Indexable
Never
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { FlatList, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native"
import { useFocusEffect } from "@react-navigation/native";

import { CalendarPopup } from "../../../component/common/CalendarPopup";
import { CircularIconGraph } from "../../../component/common/CircularIconGraph"
import CustomHeader from "../../../component/common/CustomHeader"
import GredientBg from "../../../component/common/gredientBg"
import { ListWithTitle } from "../../../component/common/ListWithTitle"
import { SheetModal } from "../../../component/common/SheetModal"
import { TrackerCard } from "../../../component/common/TrackerCard"
import { TrackerComponent } from "../../../component/common/TrackerComponent"
import { TrackerListItem } from "../../../component/common/TrackerListItem"

import CalendarIcon from '../../../assets/Icons/commons/calendar.svg'
import SearchIcon from '../../../assets/Icons/commons/search-glass.svg'
import WalkingIcon from '../../../assets/Icons/track-activity/walking.svg'

import { colors } from "../../../theme"
import fonts from "../../../assets/fonts"
import { Strings, width } from "../../../constants/constants"
import { AllTrackersModal } from "../../../component/common/AllTrackersPopup"
import { useDispatch, useSelector } from "react-redux";
import { selectDate, storeDailyGoalData, storeTrackerData } from "../../../redux/actions/users";
import { TrackersComponent } from "../../../component/track-improvement/TrackersComponent";
import { addActivityTracker, getActivityMonitor, getDailyGoal, postDailyGoal } from "../../../api";
import { ShowErrorMessage } from "../../../component/common/showErrorMessage";
import { ShowSuccessMessage } from "../../../component/common/showSuccessMessage";
import { TitleButtonComp } from "../../../component/common/TitleButtonComp";
import WeekWiseDaySelect from "../../../component/common/WeekWiseDaySelect";
import { trackScreenEvent } from "../../../utils/FirebaseTrackEvents";


interface TrackingItem {
    id: number;
    title: string;
    caloriesBurnt: number;
    icon: JSX.Element;
}
interface GoalItem {
    id: number;
    title: string;
    progress: number;
    icon: JSX.Element;
}
interface GoalCardsProps {
    item: GoalItem;
}
interface TrackingCardsProps {
    item: TrackingItem;
}

export const TrackActivityScreen = () => {
    const { userTrackersData, dailyGoalData, user, selectedDate } = useSelector(store => store.userDetails)

    useFocusEffect(
        useCallback(() => {
            const params = {
                user_id: user.user_id,
                screen_name: 'TrackActivity_Screen',
                is_event: 0,
            };
            trackScreenEvent(params);
        }, [])
    )

    const { stats } = useSelector(store => store.stats)
    const subCategoryData = [
        {
            id: 1,
            title: 'Goal',
            icon: <WalkingIcon />,
            subCategory: true,
        },
        {
            id: 2,
            title: 'Aerobic',
            icon: <WalkingIcon />,
            subCategory: true,
        },
        {
            id: 3,
            title: 'Badminton',
            icon: <WalkingIcon />,
            subCategory: true,
        },
        {
            id: 4,
            title: 'Drinking',
            icon: <WalkingIcon />,
            subCategory: true,
        },
        {
            id: 1,
            title: 'Goal',
            icon: <WalkingIcon />,
            subCategory: true,
        },
    ]
    // const reportCardData = {
    //     title: Strings.YOUR_REPORT_CARD,
    //     description: Strings.REPORT_CARD_DESCRIPTION,
    //     trackerData1: {
    //         name: 'Maintain',
    //         data: user.reach_goal.maintenance_calories,
    //         unit: 'kcal'
    //     },
    //     trackerData2: {
    //         name: 'Your Score',
    //         data: 90,
    //         unit: 'Daily avg',
    //     },
    //     trackerData3: {
    //         name: 'Target',
    //         data: user.reach_goal.target_calories,
    //         unit: 'kcal'
    //     },
    // }
    const reportCardData = {
        title: Strings.YOUR_REPORT_CARD,
        description: Strings.REPORT_CARD_DESCRIPTION,
        trackerMain: {
            name: 'Target Calories',
            data: stats.calories_intake?.data?.calories_intake_total,
            totalValue: user?.reach_goal?.target_calories,
            unit: `${user?.reach_goal?.target_calories} Kcal`,
        },
    }


    const [calendarModal, setCalendarModal] = useState<boolean>(false)
    const [showModal, setShowModal] = useState<boolean>(false)
    const [showTrackerModal, setShowTrackerModal] = useState<boolean>(false)
    const [subCategoryModal, setSubCategoryModal] = useState<boolean>(false)
    const [trackActivityModal, setTrackActivityModal] = useState<boolean>(false)
    const [selectedGoalName, setSelectedGoalName] = useState<number | string | null>('running')

    const flatListRef = useRef<FlatList<any> | null>(null);
    const dispatch = useDispatch()


    const getActivityMonitorData = () => {
        getActivityMonitor({ current_date: selectedDate }).then(val => {
            if (val.data) {
                dispatch(storeTrackerData(val.data.data[0]));
            } else {
                ShowErrorMessage('something went wrong');
            }
        }).catch(err => console.log(err))
    }

    const getDailyGoalData = () => {
        getDailyGoal({ current_date: selectedDate }).then(val => {
            if (val.data) {
                dispatch(storeDailyGoalData(val.data.data[0]));
            } else {
                ShowErrorMessage('something went wrong');
            }
        }).catch(err => console.log(err))
    }

    const addActivityData = (data) => {
        const formData = new FormData();
        formData.append('tracking_type', data?.tracker_type);
        if (data.distance) {
            formData.append('distance', data.distance);
        } if (data.duration) {
            formData.append('duration', data.duration)
        } if (data.steps) {
            formData.append('steps', data.steps)
        } if (data.category_id) {
            formData.append('category_id', data.category_id)
        } if (data.current_date) {
            formData.append('current_date', data.current_date)
        } if (data.speed) {
            formData.append('speed', data.speed)
        } if (data.additional_weight) {
            formData.append('additional_weight', data.additional_weight)
        }

        addActivityTracker(formData).then(val => {
            if (val.data) {
                setTrackActivityModal(false)
                if (val.data?.status) {
                    ShowSuccessMessage('Tracker data added successfully!')
                }
                getActivityMonitorData()
            } else {
                ShowErrorMessage('something went wrong');
            }
        }).catch(err => console.log(err))
    };

    const postDailyGoalData = (data) => {
        const formData = new FormData();
        formData.append('tracking_type', data?.tracker_type);
        if (data.distance) {
            formData.append('distance', data.distance);
        } else if (data.duration) {
            formData.append('duration', data.duration)
        } else if (data.steps) {
            formData.append('steps', data.steps)
        }
        postDailyGoal(formData).then(val => {
            if (val.data) {
                setShowModal(false)
                if (val.data?.status) {
                    ShowSuccessMessage('Daily goal set successfully!')
                }
                getActivityMonitorData()
            } else {
                ShowErrorMessage('something went wrong');
            }
        }).catch(err => console.log(err))
    };

    useEffect(() => {
        getActivityMonitorData()
        getDailyGoalData()
    }, [selectedDate])

    const renderTrackingCards = ({ item }: TrackingCardsProps) =>
    (
        <TrackerCard
            title={item?.name}
            icon={item?.icon}
            caloriesBurnt={item?.calories_burnt}
            onTrack={(val) => {
                setSelectedGoalName(val)
                setTrackActivityModal(true)
            }
            }
            distance={item?.distance}
            duration={item?.duration}
        />
    )

    const renderGoalCards = ({ item }: GoalCardsProps) => {
        return (
            <TouchableOpacity
                style={styles.goalCardContainer}>
                <CircularIconGraph
                    icon={item?.icon}
                    progress={item?.percentage}
                />
                <View>
                    <Text style={styles.goalItemTitle}>{item?.name}</Text>
                    <View style={styles.rowCenter}>
                        <Text style={styles.goalItemProgressValue}>{item?.percentage}</Text>
                        <Text style={styles.mutedSmallText}>/100%</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    const handleTrackerPress = (val) => {
        val.tracker_type = selectedGoalName;

        if (val.addAm) {
            let data = {
                tracker_type: selectedGoalName,
                duration: val.duration,
                current_date: selectedDate
            }
            if (val.distance) {
                data.distance = val.distance
            } if (val.category_id) {
                data.category_id = val.category_id
            } if (val.additional_weight) {
                data.additional_weight = val.additional_weight
            } if (val.speed) {
                data.speed = val.speed
            }
            addActivityData(data)
        } else {
            postDailyGoalData(val)
        }

    }
    return (
        <>
            <View style={{ flex: 1, }}>
                <CustomHeader
                    title='Activity Tracker'
                    renderRightIcon={() => (
                        <View style={{ ...styles.rowCenter, gap: 12, }}>
                            <TouchableOpacity style={styles.headerIconsContainer}>
                                <SearchIcon />
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={styles.headerIconsContainer}
                                onPress={() => setCalendarModal(true)}>
                                <CalendarIcon />
                            </TouchableOpacity>
                        </View>
                    )}
                />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    style={styles.container}>
                    <WeekWiseDaySelect />
                    <TrackerComponent
                        title={reportCardData.title}
                        description={reportCardData.description}
                        trackerMain={reportCardData.trackerMain}
                    />
                    <View style={styles.bottomSectionContainer}>
                        <View style={[styles.p16, { paddingRight: 30 }]}>
                            <TitleButtonComp title="Daily goal" btnText="Add goal" onBtnPress={() => setShowModal(true)} />
                        </View>

                        <FlatList
                            data={dailyGoalData?.trackers_data}
                            renderItem={renderGoalCards}
                            keyExtractor={item => item?.id}
                            horizontal
                            style={{
                                paddingVertical: 16,
                            }}
                            contentContainerStyle={{ gap: 10, paddingHorizontal: 12 }}
                            showsHorizontalScrollIndicator={false} />

                        <Text style={styles.contentTitle}>Trackers</Text>
                        <FlatList
                            data={userTrackersData?.trackers_data}
                            renderItem={renderTrackingCards}
                            numColumns={2}
                            keyExtractor={item => item?.id}
                            contentContainerStyle={{ padding: 7, paddingTop: 0, }}
                        />

                    </View>
                </ScrollView>
            </View>

            <TouchableOpacity
                style={styles.gradientButtonContainer}
                onPress={() => setShowTrackerModal(true)}>
                <GredientBg
                    style={styles.addGoalButton}>
                    <Text style={{
                        fontSize: 24,
                        color: colors.white
                    }}>+</Text>
                </GredientBg>
            </TouchableOpacity>
            {showModal &&
                <SheetModal
                    visible={showModal}
                    setVisible={setShowModal}
                    style={{ justifyContent: 'flex-end', margin: 0 }}
                    key={'track-activities-modal'}>
                    <View style={styles.modalView}>
                        <View style={styles.p16}>

                            <ListWithTitle
                                data={dailyGoalData?.trackers_data}
                                listRef={flatListRef}
                                selectedName={selectedGoalName}
                                setSelectedName={setSelectedGoalName}
                                title={'Add Daily Goal'}
                            />

                            <TrackersComponent
                                onAdd={handleTrackerPress}
                                trackerType={selectedGoalName}
                                dailyGoalTracker
                            />

                        </View>

                    </View>
                </SheetModal>}
            {showTrackerModal &&
                <SheetModal
                    visible={showTrackerModal}
                    setVisible={setShowTrackerModal}
                    key={'tracker-modal'}
                    style={styles.trackerSheet}>
                    <AllTrackersModal
                        onTrackItemPress={() => {
                            setShowTrackerModal(false)
                            setSubCategoryModal(true)
                        }}
                    />
                </SheetModal>}
            {subCategoryModal &&
                <SheetModal
                    visible={subCategoryModal}
                    setVisible={setSubCategoryModal}
                    key={'sub-category-tracker-modal'}
                    style={{ justifyContent: 'flex-end', margin: 0 }}>
                    <View style={styles.modalView}>
                        <View style={styles.p16}>
                            <Text style={{ ...styles.contentTitle, marginHorizontal: 0 }}>Swimmming</Text>
                            <FlatList
                                data={subCategoryData}
                                renderItem={({ item }) =>
                                    <TrackerListItem
                                        title={item?.title}
                                        price={item?.price}
                                        subCategory={item?.subCategory}
                                        onpress={() => {
                                            setShowTrackerModal(false)
                                            setSubCategoryModal(true)
                                        }}
                                        icon={item?.icon}
                                    />
                                }
                                keyExtractor={item => item?.id}
                                ItemSeparatorComponent={<View style={styles.verticalSeparator} />}
                                style={{ marginVertical: 20, }}
                            />
                        </View>
                    </View>
                </SheetModal>}
            {trackActivityModal &&
                <SheetModal
                    visible={trackActivityModal}
                    setVisible={setTrackActivityModal}
                    key={'track-activities-modal'}
                    style={{ justifyContent: 'flex-end', margin: 0 }}>
                    <View style={styles.modalView}>
                        <ListWithTitle
                            data={dailyGoalData?.trackers_data}
                            listRef={flatListRef}
                            selectedName={selectedGoalName}
                            setSelectedName={setSelectedGoalName}
                            title={'Track activities'}
                            key={'tracker-goal-popup'}
                        />

                        <View style={styles.p16}>

                            <TrackersComponent
                                onAdd={handleTrackerPress}
                                trackerType={selectedGoalName}
                            />

                        </View>
                    </View>
                </SheetModal>}
            {calendarModal &&
                <CalendarPopup
                    key={'calendar-popup'}
                    visible={calendarModal}
                    setVisible={setCalendarModal}
                    onSetDate={date => {
                        setCalendarModal(false)
                        dispatch(selectDate(date))
                    }}
                    onCancel={() => setCalendarModal(false)}
                />}
        </>
    )
}

const styles = StyleSheet.create({
    addGoalButton: {
        width: width * .166,
        aspectRatio: 1,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 50,
    },
    bottomSectionContainer: {
        backgroundColor: colors.white,
        flex: 1
    },
    container: {
        flex: 1,
        backgroundColor: colors.cf9f9f9,
        position: 'relative',
    },
    contentTitle: {
        fontFamily: fonts.PoppinsSemiBold,
        fontSize: 18,
        fontWeight: '600',
        color: colors.mainBlack,
        marginHorizontal: 16,
        marginVertical: 9,
        marginTop: 16,
    },
    goalCardContainer: {
        backgroundColor: colors.cf9f9f9,
        borderRadius: 43,
        padding: 8,
        paddingRight: 16,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 7,
    },
    goalItemTitle: {
        fontFamily: fonts.PoppinsMedium,
        fontSize: 14,
        fontWeight: '500',
        color: colors.mainBlack,
        textTransform: 'capitalize'
    },
    goalItemProgressValue: {
        fontFamily: fonts.PoppinsSemiBold,
        fontSize: 10,
        fontWeight: '600',
        color: colors.purple,
    },
    gradientButtonContainer: {
        position: 'absolute',
        bottom: '3.75%',
        right: '5%'
    },
    headerIconsContainer: {
        backgroundColor: colors.cf9f9f9,
        width: width * .1222,
        aspectRatio: 1,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 30,
    },
    mutedSmallText: {
        fontSize: 10,
        fontWeight: '400',
        color: colors.c999999,
        fontFamily: fonts.PoppinsRegular,
    },
    modalView: {
        backgroundColor: colors.white,
        borderTopLeftRadius: 24,
        borderTopRightRadius: 24,
    },
    p16: {
        padding: 16,
    },
    rowCenter: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    trackerSheet: {
        justifyContent: 'flex-end', margin: 0, marginTop: 80
    },
    verticalSeparator: {
        width: '100%',
        height: 1,
        backgroundColor: colors.cf9f9f9,
        marginVertical: 12,
    },
})
Leave a Comment