import React from "react";
// nodejs library that concatenates classes
import classNames from "classnames";
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
// @material-ui/icons
import InputAdornment from "@material-ui/core/InputAdornment";
import People from "@material-ui/icons/People";
import Icon from "@material-ui/core/Icon";
// core components
import Button from "/components/CustomButtons/Button.js";
import { useAuth } from "../../context/AuthContext";
import { useState, useEffect } from "react";
import { Router, useRouter } from "next/router";
import Card from "/components/Card/Card.js";
import CardBody from "/components/Card/CardBody.js";
import CardHeader from "/components/Card/CardHeader.js";
import CardFooter from "/components/Card/CardFooter.js";
import CustomInput from "/components/CustomInput/CustomInput.js";
import { getDatabase, ref, onValue, set } from "firebase/database";
import styles from "/styles/jss/nextjs-material-kit/pages/profilePage.js";
import {
SentimentVerySatisfied,
SentimentDissatisfied,
SentimentVeryDissatisfied,
} from "@material-ui/icons";
const useStyles = makeStyles(styles);
/**
* The `calculateBMI` function calculates the Body Mass Index (BMI) based on the provided height and
* weight inputs.
* @param height - Height in centimeters (cm)
* @param weight - Weight is the numerical value representing a person's weight in kilograms.
* @returns If either the `height` or `weight` parameters are falsy (null, undefined, 0, etc.), the
* function `calculateBMI` will return `null`.
*/
export const calculateBMI = (height, weight) => {
if (!height || !weight) return null;
const heightInMeters = parseFloat(height) / 100; // Convert height from cm to meters
setBMI((parseFloat(weight) / (heightInMeters * heightInMeters)).toFixed(2));
};
/**
* The function `getHealthStatus` determines a person's health status based on their BMI and then
* updates the status and provides advice accordingly.
* @param BMI - The `getHealthStatus` function takes a parameter `BMI` which represents the Body Mass
* Index of an individual. Based on the BMI value, it determines the health status of the person and
* then updates the health status and provides advice accordingly.
*/
export const getHealthStatus = (BMI) => {
let status;
if (BMI < 18.5) status = "Underweight";
else if (BMI >= 18.5 && BMI <= 24.9) status = "Normal weight";
else if (BMI >= 25 && BMI <= 29.9) status = "Overweight";
else status = "Obese";
setHealthStatus(status); // Update health status first
getAdvice(status); // Then get advice based on the updated status
};
/**
* The function `getAdvice` takes a `healthStatus` parameter and returns a random advice based on the
* health status category.
* @param healthStatus - The function `getAdvice` takes a `healthStatus` parameter and returns
* a random advice based on the given health status.
* @returns The `getAdvice` function is returning the advice based on the `healthStatus` provided as
* input. The advice is randomly selected from different arrays (`underweightAdvice`,
* `normalWeightAdvice`, `overweightAdvice`, `obeseAdvice`) based on the `healthStatus` condition.
* The selected advice is then returned by the function.
*/
export const getAdvice = (healthStatus) => {
let randomAdvice;
if (healthStatus === "Underweight") {
randomAdvice =
underweightAdvice[Math.floor(Math.random() * underweightAdvice.length)];
} else if (healthStatus === "Normal weight") {
randomAdvice =
normalWeightAdvice[Math.floor(Math.random() * normalWeightAdvice.length)];
} else if (healthStatus === "Overweight") {
randomAdvice =
overweightAdvice[Math.floor(Math.random() * overweightAdvice.length)];
} else {
randomAdvice = obeseAdvice[Math.floor(Math.random() * obeseAdvice.length)];
}
return setAdvice(randomAdvice);
};
/**
* The `renderIcon` function returns an icon based on the health status of the user.
* @returns The `renderIcon` function returns an icon component based on the health status of the user.
* The icon component is determined by the health status of the user, such as "Underweight",
* "Normal weight", "Overweight", or "Obese". The function returns different icons based on the
* health status of the user.
*/
export const renderIcon = () => {
switch (healthStatus) {
case "Underweight":
return <SentimentVeryDissatisfied color="red" />;
case "Normal weight":
return <SentimentVerySatisfied color="green" />;
case "Overweight":
return <SentimentDissatisfied color="orange" />;
case "Obese":
return <SentimentVeryDissatisfied color="red" />;
default:
return null;
}
};
/**
* The `BMU` function in JavaScript handles user BMI display and health status
* @returns The `BMI` component is returning a Card component containing user information such as
* BMI and health status. if the user has not entered their height and weight, the BMI will be unavailable.
* If the user has entered their height and weight, the BMI will be calculated and displayed. The health status
*/
export function BMI() {
const classes = useStyles();
const { currentUser } = useAuth();
const router = useRouter();
const [height, setHeight] = useState();
const [weight, setWeight] = useState();
const [BMI, setBMI] = useState(null);
const [healthStatus, setHealthStatus] = useState(null);
const [advice, setAdvice] = useState(null);
const underweightAdvice = [
"Ensure you're getting enough nutrients through a balanced diet.",
"Consider increasing your calorie intake with healthy, nutrient-dense foods.",
"Incorporate strength training exercises to build muscle mass.",
"Consult a healthcare professional for personalized advice and guidance.",
];
const normalWeightAdvice = [
"Maintain a balanced diet rich in fruits, vegetables, lean proteins, and whole grains.",
"Stay physically active by engaging in regular exercise or physical activities.",
"Focus on maintaining healthy habits to prevent weight gain in the future.",
"Keep monitoring your weight and BMI regularly to ensure you're within a healthy range.",
];
const overweightAdvice = [
"Aim to achieve gradual weight loss through a combination of diet and exercise.",
"Increase your intake of fruits, vegetables, and whole grains while reducing processed foods and added sugars.",
"Incorporate regular aerobic exercises such as walking, swimming, or cycling into your routine.",
"Seek support from a healthcare professional or a registered dietitian to develop a personalized weight loss plan.",
];
const obeseAdvice = [
"Focus on significant lifestyle changes to promote weight loss and improve overall health.",
"Consult a healthcare professional for guidance on creating a comprehensive weight loss plan.",
"Consider joining a support group or seeking help from a therapist to address emotional factors related to eating habits.",
"Prioritize long-term sustainable changes rather than quick-fix solutions for weight loss.",
];
useEffect(() => {
if (currentUser) {
// Get a reference to the Firebase Realtime Database
const db = getDatabase();
// Construct the path to the user's data in the database
const userRef = ref(db, `users/${currentUser.uid}`);
// Fetch user's data from the database
onValue(userRef, (snapshot) => {
const userData = snapshot.val(); // Retrieve the user's data
if (userData) {
// If user data exists, update the state with the name
setHeight(userData.height);
setWeight(userData.weight);
}
});
}
}, [currentUser]);
useEffect(() => {
if (height && weight) {
// Recalculate BMI when height or weight changes
calculateBMI(height, weight);
}
}, [height, weight]);
useEffect(() => {
if (BMI) {
// Get health status when BMI changes
getHealthStatus(BMI);
}
}, [BMI]);
useEffect(() => {
if (healthStatus) {
// Get advice when health status changes
getAdvice(healthStatus);
}
}, [healthStatus]);
useEffect(() => {
// Call getHealthStatus when component mounts or currentUser changes
getHealthStatus(BMI);
}, [currentUser]);
return (
<Card>
<CardBody>
<h2>
<strong>BMI</strong>
</h2>
<h2>
<strong>{BMI ? BMI : "-"}</strong>
</h2>
<h3>
<strong>{BMI ? healthStatus : "Unavailable"}</strong>
</h3>
<p>{renderIcon()}</p>
<p>{BMI ? advice : "Fill up your height & weight to get your BMI"}</p>
</CardBody>
</Card>
);
}