trackerHistoryScreen

mail@pastecode.io avatar
unknown
plain_text
a month ago
20 kB
1
Indexable
Never
import React, { useCallback, useEffect, useRef, useState } from "react"
import { FlatList, ScrollView, StyleSheet, TouchableOpacity, Text, View } from "react-native"
import { LineChart } from "react-native-chart-kit"
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import { useFocusEffect, useNavigation, useRoute } from "@react-navigation/native";

import { BarChartCustom } from "../../component/common/BarChartCustom"
import CustomHeader from "../../component/common/CustomHeader"
import { ListWithTitle } from "../../component/common/ListWithTitle"
import { ShowErrorMessage } from "../../component/common/showErrorMessage";
import { StepsHistoryCard } from "../../component/common/StepsHistoryCard"
import { WeightPickerPopup } from "../../component/common/WeightPickerPopup";

import { colors } from "../../theme"
import fonts from "../../assets/fonts"
import { historysDataItems, width } from "../../constants/constants"
import { useSelector } from "react-redux"
import { findLatestDate, findLatestDateSleepBmi } from "../../utils/Utils";
import WeekWiseDaySelect from "../../component/common/WeekWiseDaySelect";
import { fontSize } from "../../utils/fontUtils";
import { trackScreenEvent } from "../../utils/FirebaseTrackEvents";


interface InfoComponentPropTypes {
    title: string;
    value: string | number;
}
interface HistoryDataItem {
    id: number;
    title: string;
    value: number;
}
interface HistoryItem {
    id: number;
    date: string;
    stepsCount: number;
    increase: boolean;
}
interface RenderHistoryItemsProps {
    item: HistoryItem;
}

export const TrackerHistoryScreen = () => {

    const { currentTracker } = useSelector(store => store?.stats)
    const { user } = useSelector(store => store?.userDetails)
    const route = useRoute()
    const navigation = useNavigation()
    const flatlistRef = useRef<FlatList<HistoryDataItem> | null>(null);

    const currentTrackerType = route?.params?.selectedTracker
    const [selectedFilterId, setSelectedFilterId] = useState(null)
    const [weightModal, setWeightModal] = useState<boolean>(false)
    const [graphmaxValue, setgraphmaxValue] = useState(null)
    const [barGraphData, setBarGraphData] = useState({
        titlesData: [],
        valuesData: [],
    })
    useEffect(() => handleSelectFilter(1), [])
    useFocusEffect(
        useCallback(() => {
            const params = {
                user_id: user.user_id,
                screen_name: 'TrackerHistory_Screen',
                is_event: 0,
            };
            trackScreenEvent(params);
        }, [])
    )
    const trackerIcon = <MaterialCommunityIcons name={
        currentTrackerType == 'steps' ? 'walk'
            : currentTrackerType == 'burn' ? 'fire'
                : currentTrackerType
    } color={colors.purple} size={20} />

    const topGraphData = {
        labels: currentTracker?.titlesData,
        datasets: [
            {
                data: currentTracker?.valuesData
            },
        ],
    };
    const data = {
        labels: barGraphData ? barGraphData?.titlesData : ["Dec 1", "2", "3", "4", "5", "6", "7"],
        datasets: [
            {
                data: barGraphData ? barGraphData?.valuesData : [10200, 4256, 7558, 12000, 9463, 3956, 6000]
            },
        ],
    };
    const barChartConfig = {
        backgroundGradientFrom: "#fff",
        backgroundGradientFromOpacity: 0,
        backgroundGradientTo: "#fff",
        backgroundGradientToOpacity: 1,
        color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
        labelColor: (opacity = 1) => `rgba(153, 153, 153, ${opacity})`,
        strokeWidth: 2,
        barPercentage: .75,
        barRadius: 20,
        useShadowColorFromDataset: false,
        fillShadowGradientFrom: colors.GREY_F4F4F4,
        fillShadowGradientTo: '#f0f0f0',
        fillShadowGradientFromOpacity: 1,
        fillShadowGradientToOpacity: 1,
        propsForBackgroundLines: {
            strokeWidth: 2,
            stroke: colors.green
        },
    };
    const currentTrackerValue = currentTrackerType == 'weight'
        ? currentTracker?.trackerData?.data?.current_weight + 'kg'
        : currentTrackerType == 'steps'
            ? currentTracker?.trackerData?.data?.steps_number || currentTracker?.trackerData?.data?.steps
            : currentTrackerType == 'water'
                ? currentTracker?.trackerData?.data?.number_of_glass_value
                : currentTrackerType == 'burn'
                    ? (currentTracker?.trackerData?.data?.brun_total || currentTracker?.trackerData?.burn_tracking?.calories_burn)
                    : currentTrackerType == 'heart'
                        ? currentTracker?.trackerData?.data?.bpm
                        : currentTrackerType == 'bmi'
                            ? user?.reach_goal?.bmi
                            : currentTrackerType == 'sleep'
                                ? currentTracker?.trackerData?.data?.yesterday_sleeping_hour : null


    const InfoComponent: React.FC<InfoComponentPropTypes> = ({
        title,
        value
    }) => (
        <View style={styles.rowCenter}>
            <View style={styles.yellowDot} />
            <View style={styles.rowCenter}>
                <Text style={styles.infoCompTitle}>{title} : </Text>
                <Text style={styles.infoCompVal}>{value}</Text>
            </View>
        </View>
    )
    const renderHistoryCards: React.FC<RenderHistoryItemsProps> = ({ item }) => (
        <StepsHistoryCard
            title={currentTrackerType ?? 'Nil'}
            date={item?.title}
            stepsCount={item?.value}
            increase={item?.value > 0}
            icon={trackerIcon}
        />
    )
    const handleUpdateWeight = () => {
        setWeightModal(true)
    }
    const handleSelectFilter = id => {
        setSelectedFilterId(id)
        if (id === 1) {
            setBarGraphData({
                titlesData: currentTracker?.titlesData,
                valuesData: currentTracker?.valuesData
            })
        } else if (id === 2) {
            // for sleep - currentTracker?.trackerData?.month
            const titlesData = currentTracker?.trackerData?.week
                ? currentTracker?.trackerData?.week?.map(entry => entry.title)
                : currentTracker?.trackerData?.chart?.week?.map(entry => entry.title)
            const valuesData = currentTracker?.trackerData?.week
                ? currentTracker?.trackerData?.week?.map(entry => entry.value)
                : currentTracker?.trackerData?.chart?.week?.map(entry => entry.value)
            if (currentTrackerType == 'bmi') {
                ShowErrorMessage('No data present')
            } else {
                setBarGraphData({
                    titlesData: titlesData,
                    valuesData: valuesData
                })
            }
        } else if (id === 3) {
            const titlesData = currentTracker?.trackerData?.month ? currentTracker?.trackerData?.month?.map(entry => entry.title) : currentTracker?.trackerData?.chart?.month?.map(entry => entry.title)
            const valuesData = currentTracker?.trackerData?.month ? currentTracker?.trackerData?.month?.map(entry => entry.value) : currentTracker?.trackerData?.chart?.month?.map(entry => entry.value)
            if (currentTrackerType == 'bmi') {
                ShowErrorMessage('No data present')
            } else {
                setBarGraphData({
                    titlesData: titlesData,
                    valuesData: valuesData
                })
            }
        } else if (id === 4) {
            const titlesData = currentTracker?.trackerData?.year ? currentTracker?.trackerData?.year?.map(entry => entry.title) : currentTracker?.trackerData?.chart?.month?.map(entry => entry.title)
            const valuesData = currentTracker?.trackerData?.year ? currentTracker?.trackerData?.year?.map(entry => entry.value) : currentTracker?.trackerData?.chart?.year?.map(entry => entry.value)
            if (currentTrackerType == 'bmi') {
                ShowErrorMessage('No data present')
            } else {
                setBarGraphData({
                    titlesData: titlesData,
                    valuesData: valuesData
                })
            }
        }
        setAvgVal()
    }
    const setAvgVal = () => {
        setTimeout(() => {
            setgraphmaxValue(Math.max(...barGraphData?.valuesData))
        }, 800)
    }
    return (
        <>
            <CustomHeader title={currentTrackerType?.toUpperCase()} />
            <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
                <WeekWiseDaySelect isDisabled />
                <View>
                    <View style={styles.p16}>
                        <View style={styles.lineGraphContainer}>
                            <View style={{ ...styles.rowCenterApart, width: '100%', marginBottom: 12 }}>
                                <View style={{ ...styles.rowCenter, gap: 6 }}>
                                    <Text style={styles.trackerTypeTxt}>{currentTrackerType ? currentTrackerType : 'Nil'}</Text>
                                    <Text style={styles.lastUpdateTxt}>Last update-{
                                        currentTrackerType == 'bmi' ?
                                            findLatestDateSleepBmi(currentTracker?.trackerData) :
                                            findLatestDate(currentTracker?.trackerData?.chart?.day) ?? '12 Feb 2023'
                                    }</Text>
                                </View>
                                <View style={{ ...styles.rowCenter, gap: 10 }}>
                                    <View style={styles.intensityIndicator}>
                                        <Text style={styles.redText}>High</Text>
                                    </View>
                                    <Text style={styles.trackerValue}>{currentTrackerValue ?? '-'}</Text>
                                </View>
                            </View>
                            <View style={{ ...styles.rowCenterApart, width: '100%', marginBottom: 26 }}>
                                <InfoComponent title={"Height"} value={user?.height ?? 0} key='infoComponent-height-history' />
                                <InfoComponent title={"Weight"} value={user?.weight ?? 0} key='infoComponent-Weight-history' />
                                <InfoComponent title={"Age"} value={user?.age ?? '0'} key='infoComponent-age-history' />
                                <InfoComponent title={"Gender"} value={user?.gender ?? 'Male'} key='infoComponent-gender-history' />
                            </View>
                            <ScrollView horizontal>
                                {currentTracker?.titlesData?.length > 0 ? <LineChart
                                    data={topGraphData}
                                    width={width * 2}
                                    height={220}
                                    yAxisInterval={1}
                                    chartConfig={{
                                        backgroundGradientFromOpacity: 0,
                                        backgroundGradientToOpacity: 0,
                                        color: (opacity = 1) => `rgba(236, 110, 110, ${1})`,
                                        labelColor: (opacity = 1) => `rgba(153, 153, 153, ${opacity})`,
                                        style: {
                                            borderRadius: 16,
                                        },
                                        propsForDots: {
                                            r: "0",
                                        },
                                        propsForBackgroundLines: {
                                            stroke: 'rgba(0,0,0,.125)',
                                        },
                                        fillShadowGradientFrom: 'rgba(236, 110, 110, 0.47)',
                                        fillShadowGradientTo: 'white',
                                        fillShadowGradientFromOffset: 0,
                                        fillShadowGradientFromOpacity: 1,
                                        fillShadowGradientToOpacity: 0,
                                    }}
                                    bezier
                                    style={{
                                        marginVertical: 8,
                                        borderRadius: 16,
                                        marginLeft: 14
                                    }}
                                    withHorizontalLines={false}
                                />
                                    : <View style={styles.noDataContainer}>
                                        <Text style={styles.redText}>No data found ...</Text>
                                    </View>
                                }
                            </ScrollView>
                            <Text style={styles.yAxisLabel}>BMI Rates</Text>
                            <Text style={styles.dateTxt}>Date</Text>
                        </View>
                        <TouchableOpacity
                            disabled
                            onPress={handleUpdateWeight}
                            style={styles.updateButtonContainer}>
                            <Text style={styles.updateTxt}>Update {currentTrackerType}</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.bottomContainer}>
                        <ListWithTitle
                            title={'My progress'}
                            data={historysDataItems}
                            selectedName={selectedFilterId}
                            setSelectedName={handleSelectFilter}
                            key={'my-progress-history-tracker'}
                            listRef={flatlistRef}
                            extraPadding
                        />
                        <BarChartCustom
                            chartConfig={barChartConfig}
                            data={data}
                            key={'custom-bar-chart-track-history'}
                            graphWidth={barGraphData?.titlesData?.length > 25 ? width * 2 : width}
                            showXAxis
                            showAverage
                            maxDataValue={graphmaxValue}
                            trackerType={currentTrackerType}
                        />

                        <View style={styles.historyContainer}>
                            <Text style={styles.historyTxt}>History</Text>
                            <FlatList
                                data={
                                    selectedFilterId === 1
                                        ? currentTracker?.trackerData?.chart?.day
                                        : selectedFilterId === 2
                                            ? currentTracker?.trackerData?.chart?.week
                                            : selectedFilterId === 3
                                                ? currentTracker?.trackerData?.chart?.month
                                                : selectedFilterId === 4 ?
                                                    currentTracker?.trackerData?.chart?.year
                                                    : null
                                }
                                keyExtractor={item => item?.id}
                                renderItem={renderHistoryCards}
                                contentContainerStyle={{ gap: 12 }}
                                style={{ marginVertical: 20 }}
                            />
                        </View>

                        {weightModal &&
                            <WeightPickerPopup
                                visible={weightModal}
                                setVisible={setWeightModal}
                                key={'weight-picker-modal'}
                                onUpdate={() => { }}
                            />}
                    </View>
                </View>
            </ScrollView>
        </>
    )
}
const styles = StyleSheet.create({

    bottomContainer: {
        backgroundColor: colors.white,
        borderTopLeftRadius: 24,
        borderTopRightRadius: 24,
        padding: 16,
        paddingTop: 24
    },
    container: {
        flex: 1,
        backgroundColor: colors.cf9f9f9,
    },
    dateButtonContainer: {
        backgroundColor: colors.white,
        width: '100%',
        padding: 6,
        borderRadius: 12,
        alignItems: 'center'
    },
    dateTxt: {
        fontSize: fontSize.fs10,
        fontFamily: fonts.PoppinsRegular,
        color: colors.c666666
    },
    lastUpdateTxt: {
        fontSize: fontSize.fs10,
        fontFamily: fonts.PoppinsRegular,
        color: colors.c999999
    },
    redText: {
        fontSize: fontSize.fs12,
        fontFamily: fonts.PoppinsMedium,
        color: colors.cEC6E6E,
    },
    historyTxt: {
        fontSize: fontSize.fs18,
        fontFamily: fonts.PoppinsSemiBold,
        color: colors.c222222
    },
    infoCompTitle: {
        fontSize: fontSize.fs12,
        fontFamily: fonts.PoppinsRegular,
        color: colors.c666666
    },
    infoCompVal: {
        fontSize: fontSize.fs12,
        fontFamily: fonts.PoppinsSemiBold,
        color: colors.c666666
    },
    updateTxt: {
        fontSize: fontSize.fs14,
        fontFamily: fonts.PoppinsSemiBold,
        color: colors.white,
    },
    trackerValue: {
        fontSize: fontSize.fs28,
        fontFamily: fonts.PoppinsBold,
        color: colors.cEC6E6E,
    },
    historyContainer: {
        marginTop: 32,
    },
    intensityIndicator: {
        backgroundColor: colors.lightRedBg,
        padding: 4,
        paddingHorizontal: 12,
        borderRadius: 16,
        alignItems: 'center'
    },
    lineGraphContainer: {
        alignItems: 'center',
        marginVertical: 14,
        backgroundColor: colors.white,
        padding: 16,
        borderRadius: 12,
        position: 'relative',
        paddingBottom: 10,
        zIndex: 99,
    },
    noDataContainer: {
        height: width / 2,
        alignItems: 'center',
        justifyContent: 'center'
    },
    p16: {
        padding: 16,
    },
    rowCenter: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    rowCenterApart: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    trackerTypeTxt: {
        fontSize: fontSize.fs16,
        fontFamily: fonts.PoppinsSemiBold,
        color: colors.black,
        textTransform: 'capitalize'
    },
    updateButtonContainer: {
        padding: 12,
        borderRadius: 12,
        width: '100%',
        alignItems: 'center',
        marginTop: -30,
        paddingTop: 24,
        backgroundColor: colors.GREEN_3BBF51_20
    },
    yAxisLabel: {
        fontSize: 10,
        fontFamily: fonts.PoppinsRegular,
        color: colors.c999999,
        position: 'absolute',
        left: -5,
        top: '50%',
        bottom: '50%',
        transform: 'rotate(-90deg)'
    },
    yellowDot: {
        width: 5,
        height: 5,
        backgroundColor: colors.mangoYellow,
        borderRadius: 18,
        marginRight: 4
    },
})
Leave a Comment