import React, { useState, useRef, useEffect } from "react"; import { View, Text, Image, StyleSheet, TouchableOpacity, Animated, BackHandler, FlatList, ScrollView, TextInput, } from "react-native"; import axios from "axios"; import AsyncStorage from "@react-native-async-storage/async-storage"; import Container from "../components/Container"; import CardRecord from "../components/CardRecord"; const ScreenFasting = ({ navigation }) => { const [token, setToken] = useState(null); const [profileId, setProfileId] = useState(null); const [profileName, setProfileName] = useState(null); const [profileSex, setProfileSex] = useState(null); const [profileDob, setProfileDob] = useState(null); const [profileAge, setProfileAge] = useState(null); const [whenLastEat, setWhenLastEat] = useState(""); // YYYY-MM-DD HH:MM:SS const [whenLastDrink, setWhenLastDrink] = useState(""); // YYYY-MM-DD HH:MM:SS const [recordList, setRecordList] = useState([]); const getToken = async () => { const savedToken = await AsyncStorage.getItem("auth_token"); if (savedToken !== null) { setToken(savedToken); } else { // navigation.navigate("Profile"); } }; const HttpRequest = (url, body, conf, handle) => { // string, object, object axios .post(url, body, conf) .then((response) => { handle(response.data); }) .catch((error) => { console.error("Terjadi kesalahan:", error.stack); }); }; const handleProfileDetail = (data) => { if (data.status === "success") { setProfileId(data.data.id); setProfileName(data.data.name); setProfileSex(data.data.sex); setProfileDob(data.data.dob); if (data.data.dob !== null) { const tanggalLahir = new Date(data.data.dob); const today = new Date(); const umur = today.getFullYear() - tanggalLahir.getFullYear(); const bulanSekarang = today.getMonth() - tanggalLahir.getMonth(); let umurTerupdate; if ( bulanSekarang < 0 || (bulanSekarang === 0 && today.getDate() < tanggalLahir.getDate()) ) { umurTerupdate = umur - 1; } else { umurTerupdate = umur; } setProfileAge(umurTerupdate); } } }; const fetchProfileDetail = async () => { try { const url = "https://uas.ditaajipratama.net/api/checkcare/profile/detail"; const body = {}; const auth_token = await AsyncStorage.getItem("auth_token"); const config = { headers: { Authorization: `Bearer ${auth_token}`, }, }; console.log(`Bearer ${auth_token}`); console.log(token); if (auth_token !== null) { HttpRequest(url, body, config, handleProfileDetail); } } catch (error) { console.log(error.stack); } }; const calculateFastingDuration = (lastEatTime, lastDrinkTime) => { if (!lastEatTime && !lastDrinkTime) return 0; const now = new Date(); const lastEat = lastEatTime ? new Date(lastEatTime) : null; const lastDrink = lastDrinkTime ? new Date(lastDrinkTime) : null; // Use the more recent time (shorter fasting period) let lastIntake = null; if (lastEat && lastDrink) { lastIntake = lastEat > lastDrink ? lastEat : lastDrink; } else if (lastEat) { lastIntake = lastEat; } else if (lastDrink) { lastIntake = lastDrink; } if (!lastIntake) return 0; const diffMs = now - lastIntake; const diffHours = diffMs / (1000 * 60 * 60); return Math.max(0, diffHours); }; const quickResult = (whenLastEat, whenLastDrink) => { var title = "Cek Puasa"; var message = "Masukkan waktu makan dan minum terakhir"; var image = require("../assets/illustration/menu/medicine.png"); // You'll change this const fastingHours = calculateFastingDuration(whenLastEat, whenLastDrink); if (fastingHours === 0) { title = "Cek Puasa"; message = "Masukkan waktu makan dan minum terakhir"; } else if (fastingHours < 12) { title = "Puasa Pendek"; message = `Anda telah berpuasa selama ${fastingHours.toFixed(1)} jam`; } else if (fastingHours >= 12 && fastingHours < 16) { title = "Intermittent Fasting"; message = `Anda telah berpuasa selama ${fastingHours.toFixed(1)} jam`; } else if (fastingHours >= 16 && fastingHours < 24) { title = "Extended Fasting"; message = `Anda telah berpuasa selama ${fastingHours.toFixed(1)} jam`; } else { title = "Puasa Panjang"; message = `Anda telah berpuasa selama ${fastingHours.toFixed( 1 )} jam - Konsultasi dengan dokter`; } return { title, message, image, fastingHours }; }; const reqRecordList = async () => { try { const url = "https://uas.ditaajipratama.net/api/checkcare/fasting/list"; const body = {}; const auth_token = await AsyncStorage.getItem("auth_token"); const config = { headers: { Authorization: `Bearer ${auth_token}`, }, }; const handle = (data) => { setRecordList(data); }; if (auth_token !== null) { HttpRequest(url, body, config, handle); } } catch (error) { console.log(error.stack); } }; const reqAdd = async () => { try { const url = "https://uas.ditaajipratama.net/api/checkcare/fasting/add"; const body = { when_last_eat: whenLastEat, when_last_drink: whenLastDrink, }; const auth_token = await AsyncStorage.getItem("auth_token"); const config = { headers: { Authorization: `Bearer ${auth_token}`, }, }; const handle = (data) => { reqRecordList(); setWhenLastEat(""); setWhenLastDrink(""); }; if (auth_token !== null) { HttpRequest(url, body, config, handle); } } catch (error) { console.log(error.stack); } }; const ListItem = ({ item }) => { const result = quickResult(item.when_last_eat, item.when_last_drink); return ( {item.when} Puasa: {result.fastingHours.toFixed(1)} jam {result.title} ); }; useEffect(() => { getToken(); fetchProfileDetail(); reqRecordList(); }, []); return ( {quickResult(whenLastEat, whenLastDrink).title} {`Durasi: ${quickResult( whenLastEat, whenLastDrink ).fastingHours.toFixed(1)} jam`} {quickResult(whenLastEat, whenLastDrink).message} setWhenLastEat(text)} value={whenLastEat} /> setWhenLastDrink(text)} value={whenLastDrink} /> Submit } keyExtractor={(item, index) => index.toString()} /> ); }; const styles = StyleSheet.create({ headerRow: { flexDirection: "row", alignItems: "center", }, illustration: { width: 100, height: 100, }, illustrationContainer: { marginRight: 16, }, textContainer: { flex: 1, }, title: { fontSize: 28, fontWeight: "bold", color: "#111", }, datetime: { fontSize: 12, color: "#444", marginVertical: 4, }, description: { fontSize: 14, color: "#333", maxWidth: 320, marginBottom: 16, }, inputColumn: { width: "100%", marginBottom: 10, }, inputForm: { borderWidth: 1, borderColor: "#ccc", borderRadius: 30, paddingVertical: 10, paddingHorizontal: 16, marginVertical: 6, backgroundColor: "#fff", color: "#333", }, inputButtonSubmit: { borderRadius: 30, paddingVertical: 12, marginVertical: 6, backgroundColor: "#007bff", }, submitText: { textAlign: "center", color: "#fff", fontWeight: "600", }, resultDate: { flex: 1, color: "#333", }, resultValue: { flex: 1, textAlign: "center", color: "#111", fontWeight: "500", }, resultStatus: { flex: 1, textAlign: "right", fontWeight: "bold", }, }); export default ScreenFasting;