import React from "react";
import { View, ImageBackground, ScrollView } from "react-native";
import { Text, List, Menu, Button } from "react-native-paper";
import i18n from "../i18nMessages.js";
import Moment from 'moment';
import 'moment/min/locales';
Moment.locale(i18n.locale);
import API from '../API.js';
import { useSnapshot } from 'valtio';
import GlobalState from '../contexts/GlobalState.js';
import ProfileCardHorizontal from "../components/ProfileCardHorizontal.js";
import * as Updates from 'expo-updates';
import AsyncStorage from '@react-native-async-storage/async-storage';

let MenuView = ({ navigation }) => {
    const [value, setValue] = React.useState(i18n.locale);
    const [languageMenuVisible, setLanguageMenuVisible] = React.useState(false);
    const [myProfiles, setMyProfiles] = React.useState([]);
    const gState = useSnapshot(GlobalState);
    const viewer = gState.me;

    React.useEffect(() => {
        let subscribed = true;
        let getData = async () => {
            const r = await API.getMyProfiles();
            if (!subscribed) return;
            setMyProfiles(Array.isArray(r?.profiles) ? r.profiles : []);
        }
        getData();
        return () => {
            subscribed = false;
        }
    }, []);

    let changeLang = async (locale) => {
        i18n.locale = locale;
        Moment.locale(locale);
        setValue(locale);
        await AsyncStorage.removeItem('feed');
        //Change local on profile then reload
    }
    const languageOptions = [
        { value: "es", label: i18n.t("message.languageSpanish") },
        { value: "en", label: i18n.t("message.languageEnglish") },
        { value: "da", label: i18n.t("message.languageDanish") },
        { value: "fr", label: i18n.t("message.languageFrench") },
    ];
    const currentLanguageLabel = languageOptions.find((opt) => opt.value === value)?.label || i18n.t("message.languageEnglish");

    const profileLists = myProfiles.map((profile) => {
        const profileInfo = profile?.profile || {};
        const DefaultPhoto = "https://social.emmint.com/uploads/e6f9be6d665dc43417701bf16a90122c.png";
        let photoUrl = profileInfo.photo ? 'https://social.emmint.com/' + profileInfo.photo : DefaultPhoto;
        let icon = profile._id ? (!profile.isGroup ? "person-outline" : "group") : '';
        icon = icon === "person-outline" && profile.subscription && profile.subscription > (new Date() - 0) ? "assignment-ind" : icon;
        icon = icon === "group" && profile.isCourse ? "subscriptions" : icon;
        icon = icon === "group" && profile.isPrivate ? "screen-lock-portrait" : icon;
        return <>
            <List.Item
                title={(profileInfo.firstName || "") + " " + (profileInfo.lastName || "")}
                description={profileInfo.description || ""}
                onPress={async () => { 
                    await API.changeProfile(profile._id);
                    GlobalState.me = await API.getMe();
                }}
                left={props => <List.Icon {...props} icon={icon} />}
                titleStyle={{fontWeight:"bold"}}
                descriptionNumberOfLines={3}
                key={profile._id}
            />
        </>
    })

    return (
        <ScrollView>
            <ImageBackground source={require("../assets/settings.png")}
                style={{ paddingTop: 10 }}
                imageStyle={{ resizeMode: "contain", opacity: 0.05 }}
            >
                <ProfileCardHorizontal profileObj={viewer} skipFollow={true} skiptOnPress={true} key={viewer._id} />
                <List.Accordion
                    title={i18n.t("message.changeActiveProfile")}
                    left={props => <List.Icon {...props} icon="published-with-changes" />}
                    
                >
                    {profileLists}
                </List.Accordion>
                <List.Section title={i18n.t("message.userActions")}>
                    <List.Item key='ProfileEditor' title={i18n.t('message.profile')} onPress={() => { navigation.navigate("ProfileSettings") }} left={props => <List.Icon {...props} icon="person" />} />
                    <List.Item key='GlobalChat' title='Global Chat' onPress={() => { navigation.navigate("GlobalChat") }} left={props => <List.Icon {...props} icon="chat" />} />
                    <List.Item key='LiveCaptions' title={i18n.t("message.liveCaptions")} onPress={() => { navigation.navigate("LiveCaptions") }} left={props => <List.Icon {...props} icon="closed-caption" />} />
                    <List.Item key='Settings' title={i18n.t('message.settings')} left={props => <List.Icon {...props} icon="settings" />} />
                    <List.Item key="Logout" title={i18n.t('message.logout')} onPress={() => { navigation.navigate("Logout") }} left={props => <List.Icon {...props} icon="logout" />} />
                </List.Section>
                <List.Section title={i18n.t("message.fellowshipApp")}>
                    <List.Item key='Bible' title={i18n.t('message.bible') || 'Bible'} onPress={() => { navigation.navigate("Bible") }} left={props => <List.Icon {...props} icon="menu-book" />} />
                    <List.Item key='Invite' title={i18n.t('message.invite')} onPress={() => { navigation.navigate("Invite") }} left={props => <List.Icon {...props} icon="person-add" />} />
                    <List.Item key='About' title={i18n.t('message.about')} left={props => <List.Icon {...props} icon="more" />} />
                </List.Section>
                <View style={{ padding: 10 }}>
                    <Text>{i18n.t("message.appLanguage")}:</Text>
                    <Menu
                        visible={languageMenuVisible}
                        onDismiss={() => setLanguageMenuVisible(false)}
                        anchor={
                            <Button mode="outlined" onPress={() => setLanguageMenuVisible(true)}>
                                {currentLanguageLabel}
                            </Button>
                        }
                    >
                        {languageOptions.map((option) => (
                            <Menu.Item
                                key={option.value}
                                title={option.label}
                                onPress={() => {
                                    changeLang(option.value);
                                    setLanguageMenuVisible(false);
                                }}
                            />
                        ))}
                    </Menu>
                </View>
                <View style={{ padding: 10, alignContent: "center", flex: 1 }}>
                    <Text>{i18n.t("message.version")}: {Updates.runtimeVersion}</Text>
                    <Text>{i18n.t("message.channel")}: {Updates.Channel}</Text>
                </View>
            </ImageBackground>
        </ScrollView>
    )
}

export default MenuView;
