import React, { useState, useRef, useEffect } from 'react';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { StyleSheet, Text, View, Image, TouchableOpacity, Animated, BackHandler, FlatList, Button, TextInput } from 'react-native';
import Container from '../components/Container';

const ScreenProfile = ({ navigation }) => {
    const [username, setUsername] = useState(null);
    const [password, setPassword] = useState(null);

    const [token, setToken] = useState(null); // Sebagai kunci profile

    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 storeToken = async (auth_token) => {
        await AsyncStorage.setItem('auth_token', auth_token);
    };
    const getToken = async () => {
        const savedToken = await AsyncStorage.getItem('auth_token');
        if (savedToken !== null) {
            setToken(savedToken);
        }
    };
    const removeToken = async () => {
        await AsyncStorage.removeItem('auth_token');
        setToken(null);
    };

    const HttpRequest = (url,body,conf,handler) => {
        axios.post(url,body,conf).then(response => {
            handler(response.data);
        }).catch(error => {
            console.error('Terjadi kesalahan:', error.stack);
        });
    };

    const handleLogin = (data) => {
        if (data.status === 'success') {
            storeToken(data.data.jwt);
            getToken();
            navigation.goBack();
        }
    };
    const handleLogout = (data) => {
        if (data.status === 'success') {
            removeToken();
            navigation.goBack();
        }
    };

    const submitLogin = () => {
        const url = 'https://asrul.costafuture.com/api/auth/login';
        const body = {
            username:username,
            password:password
        };
        const config = {};
        HttpRequest(url, body, config, handleLogin);
    };
    const submitLogout = () => {
        const url = 'https://asrul.costafuture.com/api/auth/logout';
        const body = {};
        const config = {
            headers: {
                Authorization: `Bearer ${token}`
            }
        };
        HttpRequest(url, body, config, handleLogout);
    };
    
    return (
        <View style={styles.container}>
            <Text>Ini halaman Profile</Text>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

export default ScreenProfile;
