import React, { useEffect, useState } from 'react';
import {View, StyleSheet, Text, AppState } 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";
import axios from "axios";
export const API_URL = process.env.EXPO_PUBLIC_API_URL;

const Index = () => {
    const theme = useTheme();
    const [isProfileActive, setProfileActive] = useState(false);
    const [userId, setUserId] = useState("");
    const [userName, setUserName] = useState("");
    const [userImage, setUserImage] = useState("");
    const [userStatus, setUserStatus] = useState("none");
    const [userDataChanged, setUserDataChanged] = useState(false);
    const [isLoading, setIsLoading] = useState(true);  // New loading state
    const [appState, setAppState] = useState(AppState.currentState);

    useEffect(() => {
        const loadUserData = async () => {
            try {
                const storedUserId = await AsyncStorage.getItem("userId");
                const storedUserName = await AsyncStorage.getItem("userName");
                const storedUserImage = await AsyncStorage.getItem("userImage");
                console.log("User Id: ", storedUserId);
                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]);

    useEffect(() => {
        const handleAppStateChange = (nextAppState: string) => {
            //console.log("App state", appState);
            //console.log("Next App state", nextAppState);
            if (appState.match(/inactive|background/) && nextAppState === "active") {
                // When the app comes to the foreground, fetch the status
                if (!isLoading) {
                    fetchCurrentStatus().then()
                } else {
                    console.log("Waiting for loading to complete before fetching status...");
                }
            }
            setAppState(AppState.currentState);
        };

        const listener = AppState.addEventListener("change", handleAppStateChange);

        // Cleanup listener on unmount
        return () => {
            listener.remove();
        };
    }, [appState]);

    const fetchCurrentStatus = async () => {
        try {
            const response = await axios.post(API_URL + "/get", { id: userId });
            console.log("response: ", response);
            if (response.data?.status) {
                setTimeout(() => {
                    setUserStatus("none"); // Reset status
                }, 0)
            }
        } catch (error) {
            console.error("Error fetching status:", error);
        }
    };

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

    return (
        <View style={[styles.container, { backgroundColor: theme.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;
