import React, { useEffect, useState } from 'react';
import { View, StyleSheet } from "react-native";
import { useTheme } from "react-native-paper";
import { v4 as uuidv4 } from "uuid";
import AsyncStorage from "@react-native-async-storage/async-storage";
import ProfileScreen from "@/app/ProfileScreen";
import StatusPage from "@/app/StatusPage";



const Index = () => {
    const { colors } = useTheme();
    const [isProfileActive, setProfileActive] = useState(false);
    const [userId, setUserId] = useState(uuidv4());
    const [userName, setUserName] = useState("");
    const [userImage, setUserImage] = useState("");

    useEffect(() => {
        const loadUserData = async () => {
            try {
                const storedUserId = await AsyncStorage.getItem("userId");
                const storedUserName = await AsyncStorage.getItem("userName");
                const storedUserImage = await AsyncStorage.getItem("userImage");
                if(storedUserId) {
                    setUserId(storedUserId || uuidv4());
                    setUserName(storedUserName || "");
                    setUserImage(storedUserImage || "");
                    setProfileActive(false);
                }else{
                    setUserId(uuidv4());
                    setUserName("");
                    setUserImage("");
                    setProfileActive(true);
                }

            } catch (error) {
                console.error("Error loading user data:", error);
            }
        };
        loadUserData();
    }, []);

    useEffect(() => {
        const saveUserData = async () => {
            try {
                await AsyncStorage.setItem("userId", userId);
                await AsyncStorage.setItem("userName", userName);
                await AsyncStorage.setItem("userImage", userImage);
            } catch (error) {
                console.error("Error saving user data:", error);
            }
        };
        saveUserData();
    }, [userId, userName, userImage]);

    return (
        <View style={[styles.container,{ backgroundColor: colors.background }]}>
            <StatusPage
                toggleProfile={() => setProfileActive(true)}
                id={userId}
                name={userName}
                image={userImage}
                isProfileActive={isProfileActive}
            />
            <ProfileScreen
                visible={isProfileActive}
                id={userId}
                name={userName}
                setName={setUserName}
                image={userImage}
                setImage={setUserImage}
                onClose={() => setProfileActive(false)}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: { flex: 1, alignItems: "stretch" },
});

export default Index;
