trackerHistoryScreen

 avatar
unknown
plain_text
a year ago
20 kB
7
Indexable
import React, { 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 { 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 routes from "../../routes/routes";
import useHardwareBackButton from "../../utils/backHandler";


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 { userData } = 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: [],
    })
    useHardwareBackButton()
    useEffect(()=>setSelectedFilterId(1),[])
    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
            : 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'
                            ? userData?.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.fs12ppReg666}>{title} : </Text>
                <Text style={styles.fs12ppSb666}>{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()}
                onBack={() => navigation.replace(routes.statBurn,{origin:'burn-session'})}
            />
            <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.fs16ppSb000, textTransform: 'capitalize' }}>{currentTrackerType ? currentTrackerType : 'Nil'}</Text>
                                    <Text style={styles.fs10ppReg999}>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.fs12ppMedRed}>High</Text>
                                    </View>
                                    <Text style={styles.fs28ppBldRed}>{currentTrackerValue ?? '0'}</Text>
                                </View>
                            </View>
                            <View style={{ ...styles.rowCenterApart, width: '100%', marginBottom: 26 }}>
                                <InfoComponent title={"Height"} value={userData?.height ?? 0} key='infoComponent-height-history' />
                                <InfoComponent title={"Weight"} value={userData?.weight ?? 0} key='infoComponent-Weight-history' />
                                <InfoComponent title={"Age"} value={userData?.age ?? '0'} key='infoComponent-age-history' />
                                <InfoComponent title={"Gender"} value={userData?.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,
                                        // fillShadowGradientOpacity: 0,
                                    }}
                                    bezier
                                    style={{
                                        marginVertical: 8,
                                        borderRadius: 16,
                                        marginLeft: 14
                                    }}
                                    withHorizontalLines={false}
                                />
                                    : <View style={styles.noDataContainer}>
                                        <Text style={styles.fs12ppMedRed}>No data found ...</Text>
                                    </View>
                                }
                            </ScrollView>
                            <Text style={styles.yAxisLabel}>BMI Rates</Text>
                            <TouchableOpacity style={styles.dateButtonContainer}>
                                <Text style={styles.fs10ppReg666}>Date</Text>
                            </TouchableOpacity>
                        </View>
                        <TouchableOpacity onPress={handleUpdateWeight} style={styles.updateButtonContainer}>
                            <Text style={styles.fs14ppSbWhite}>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.fs18ppSb000, color: colors.c222222 }}>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'
    },
    fs10ppReg666: {
        fontSize: 10,
        fontFamily: fonts.PoppinsRegular,
        fontWeight: '400',
        color: colors.c666666
    },
    fs10ppReg999: {
        fontSize: 10,
        fontFamily: fonts.PoppinsRegular,
        fontWeight: '400',
        color: colors.c999999
    },
    fs12ppMedRed: {
        fontSize: 12,
        fontFamily: fonts.PoppinsMedium,
        fontWeight: '500',
        color: colors.cEC6E6E,
    },
    fs12ppReg666: {
        fontSize: 12,
        fontFamily: fonts.PoppinsRegular,
        fontWeight: '400',
        color: colors.c666666
    },
    fs12ppSb666: {
        fontSize: 12,
        fontFamily: fonts.PoppinsSemiBold,
        fontWeight: '600',
        color: colors.c666666
    },
    fs14ppSbWhite: {
        fontSize: 14,
        fontFamily: fonts.PoppinsSemiBold,
        fontWeight: '600',
        color: colors.white,
    },
    fs16ppSb000: {
        fontSize: 16,
        fontFamily: fonts.PoppinsSemiBold,
        fontWeight: '600',
        color: colors.black
    },
    fs18ppSb000: {
        fontSize: 18,
        fontFamily: fonts.PoppinsSemiBold,
        fontWeight: '600',
        color: colors.black,
    },
    fs28ppBldRed: {
        fontSize: 28,
        fontFamily: fonts.PoppinsBold,
        fontWeight: '700',
        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'
    },
    updateButtonContainer: {
        padding: 12,
        backgroundColor: colors.green,
        borderRadius: 12,
        width: '100%',
        alignItems: 'center',
        marginTop: -30,
        paddingTop: 24
    },
    yAxisLabel: {
        fontSize: 10,
        fontFamily: fonts.PoppinsRegular,
        fontWeight: '400',
        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
    },
})
Editor is loading...
Leave a Comment