import React, { useEffect, useState } from 'react';
import {View, StyleSheet, Text } 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";
import Nav from "@/app/Nav";

const Index = () => {
    const { colors } = useTheme();
    const [isProfileActive, setProfileActive] = useState(false);
    const [userId, setUserId] = useState("");
    const [userName, setUserName] = useState("");
    const [userImage, setUserImage] = useState("");
    const [userStatus, setUserStatus] = useState("");
    const [userDataChanged, setUserDataChanged] = useState(false);
    const [isLoading, setIsLoading] = useState(true);  // New loading state

    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);
                }
                console.log("Loading data ", userId);
            } catch (error) {
                console.error("Error loading user data:", error);
            } finally {
                setIsLoading(false);  // Mark loading as complete
            }
        };
        loadUserData();
    }, []);

    useEffect(() => {
        if (!userDataChanged) return;

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

    if (isLoading) {
        console.log("Still loading");
        return (
            <View style={[styles.container, { backgroundColor: colors.background, justifyContent: 'center', alignItems: 'center' }]}>
                <Text>Loading...</Text>
            </View>
        );
    }

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

const styles = StyleSheet.create({
    container: { flex: 1, alignItems: "stretch" },
    imageBackground: {
        position: "absolute",  // Allows child elements to layer on top
        width: "100%",         // Ensure full coverage of the column
        height: "100%",        // Fully stretches to column height
        resizeMode: "cover",   // Ensures it fits well
        opacity: 0.3,          // Fades the image
    },
});

export default Index;
