import React from "react";
import { View, ImageBackground, ScrollView, Platform } from "react-native";
import { Text, TextInput, Button, Divider, Checkbox, Menu } from "react-native-paper";
import i18n from "../i18nMessages.js";
import Moment from 'moment';
import 'moment/min/locales';
import ProfileCardHorizontal from "../components/ProfileCardHorizontal.js";
Moment.locale(i18n.locale);
import { useSnapshot } from 'valtio';
import GlobalState from '../contexts/GlobalState.js';
import API from "../API.js";
import * as ImagePicker from 'expo-image-picker';
import { useNavigation } from '@react-navigation/native';



let ProfileSettings = () => {
    const navigation = useNavigation();
    const gState = useSnapshot(GlobalState);
    const viewer = gState.me;
    const viewerProfile = viewer?.profile || {};
    const [photo, setPhoto] = React.useState(null);
    const [name, setName] = React.useState(viewerProfile.firstName || "");
    const [lastName, setLastName] = React.useState(viewerProfile.lastName || "");
    const [photoUrl, setphotoUrl] = React.useState(viewerProfile.photo || "");
    const [language, setLanguage] = React.useState(viewerProfile.language || "en");
    const [updateKey, setUpdateKey] = React.useState(0);
    const [description, setDescription] = React.useState(viewerProfile.description || "");
    const [uploading, setUploading] = React.useState(false);
    const [languageMenuVisible, setLanguageMenuVisible] = React.useState(false);
    const previewProfile = {
        ...(GlobalState.me || {}),
        profile: {
            ...(GlobalState.me?.profile || {}),
            firstName: name,
            lastName: lastName,
            description: description,
            language: language,
            photo: photoUrl,
        },
    };

    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 === language)?.label || i18n.t("message.languageEnglish");

    const pickImage = async () => {
        if (uploading) return;
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 0.85,
            //allowsMultipleSelection: true,
        });
        if (!result.canceled) {
            setUploading(true);
            setPhoto(result);
            let newPhotoURL = await handleUploadPhoto(result.assets[0]);
            if (newPhotoURL !== "") {
                setphotoUrl(newPhotoURL);
                if (!GlobalState.me.profile) GlobalState.me.profile = {};
                GlobalState.me.profile.photo = newPhotoURL;
                await updateProfile({ photo: newPhotoURL }, false);
                setUpdateKey((k) => k + 1);
            } else {
                alert("Could not upload photo. Please try another image.");
            }
            setPhoto(null);
            setUploading(false);
        }
    };

    const handleUploadPhoto = async (photo) => {
        console.log(photo)
        if (!photo) return '';
        const uri =
            Platform.OS === "android"
                ? photo.uri
                : photo.uri.replace("file://", "");

        console.log(uri);
        const filename = photo.uri.split("/").pop() || "image.jpg";
        const match = /\.(\w+)$/.exec(filename);
        const ext = (match?.[1] || "jpg").toLowerCase();
        const type = ext === "heic" || ext === "heif" ? "image/heic" : `image/${ext}`;
        const formData = new FormData();
        formData.append("banner", {
            uri,
            name: `image.${ext}`,
            type,
        });
        let uploadedFile = '';
        try {
            uploadedFile = await fetch("https://social.emmint.com/upload.php", {
                method: "POST",
                body: formData,
                headers: { "Content-Type": "multipart/form-data" }
            })
                .then((res) => res.json())
                .then((data) => {
                    console.log(data);
                    return data?.fileName || '';
                });
            console.log(uploadedFile);
        } catch (err) {
            console.log(err);
            alert("Something went wrong uploading the photo.");
        }
        return uploadedFile;
    };

    let updateProfile = async (overrides = {}, goBackAfter = true) => {
        let currentProfile = {};
        let currentData = {};
        try {
            currentData = JSON.parse(JSON.stringify(viewer?.data || {}));
        } catch (_) {
            currentData = {};
        }
        try {
            currentProfile = {
                firstName: name,
                lastName: lastName,
                description,
                language,
                photo: overrides.photo ?? photoUrl,
            };
            console.log("updating", currentProfile);
        } catch (error) {
            alert("Error updating profile, contact administrator.");
            return;
        }
        let r = await API.updateMyProfile(currentProfile, currentData).catch((e) => {
            console.error("Profile update request failed", e);
            alert("Error updating profile, contact administrator.");
            return null;
        });
        if (!r || r.status !== "ok") {
            console.error("Profile update unexpected response", r);
            return alert("Error updating profile, contact administrator.");
        }
        const refreshedProfile = await API.getUserProfile(viewer?._id, true).catch(() => null);
        if (refreshedProfile && refreshedProfile._id) {
            GlobalState.me = {
                ...GlobalState.me,
                ...refreshedProfile,
            };
        } else {
            if (!GlobalState.me.profile) GlobalState.me.profile = {};
            GlobalState.me.profile = {
                ...GlobalState.me.profile,
                ...currentProfile,
            };
        }
        console.log(r);
        setUpdateKey((k) => k + 1);
        if (goBackAfter) {
            navigation.goBack();
        }
    }

    return (
        <ScrollView style={{
            padding: 10,
        }}>
            <ImageBackground source={require("../assets/settings.png")}
                imageStyle={{ resizeMode: "contain", opacity: 0.05 }}
                style={{ paddingBottom: 50 }}
            >
                <View style={{ paddingTop: 10 }}>
                    <ProfileCardHorizontal profileObj={previewProfile} skipFollow={true} skiptOnPress={true} key={updateKey} />
                </View>
                <Text style={{ marginBottom: 10, marginTop: 10, fontSize: 20 }}>{i18n.t("message.profileSetting")}</Text>
                <Button icon="photo" mode="outlined" onPress={pickImage}>
                    {!uploading ? i18n.t("message.updatePhoto") : i18n.t("message.uploading")}
                </Button>
                <Divider />
                <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
                    <TextInput
                        label={i18n.t("message.name")}
                        style={{ width: "48%", backgroundColor: "rgba(0,0,0,0)" }}
                        value={name}
                        onChangeText={text => setName(text)}
                    />
                    <TextInput
                        label={i18n.t("message.lastName")}
                        style={{ width: "48%", backgroundColor: "rgba(0,0,0,0)" }}
                        value={lastName}
                        onChangeText={text => setLastName(text)}
                    />
                </View>
                <TextInput
                    label={i18n.t("message.description")}
                    style={{ backgroundColor: "rgba(0,0,0,0)", marginBottom: 5 }}
                    multiline={true}
                    numberOfLines={3}
                    value={description}
                    onChangeText={text => setDescription(text)}
                />
                <Text style={{ marginBottom: 4 }}>{i18n.t("message.language")}:</Text>
                <View style={{ marginBottom: 10 }}>
                    <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={() => {
                                    setLanguage(option.value);
                                    setLanguageMenuVisible(false);
                                }}
                            />
                        ))}
                    </Menu>
                </View>
                <Button
                    mode="contained"
                    onPress={() => updateProfile({}, true)}
                    buttonColor="#c44d56"
                    textColor="#ffffff"
                    style={{ marginTop: 8 }}
                    contentStyle={{ paddingVertical: 6 }}
                >
                    {i18n.t("message.update")}
                </Button>
                {/*
                <Divider />
                <Text style={{ fontSize: 20, padding: 5, color: "#666" }}>{i18n.t("message.optional")}:</Text>
                <View style={{ flexDirection: "row", justifyContent: "space-evenly" }}>
                    <Checkbox.Item status={'unchecked'} label="Married" />
                    <Checkbox.Item status={'unchecked'} label="With Kids" />
                </View>
                <Text>{i18n.t("message.birthday")}</Text>
                <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
                    <TextInput
                        label={"Day:"}
                        style={{ width: "48%", backgroundColor: "rgba(0,0,0,0)" }}
                    //value={name}
                    //onChangeText={text => setName(text)}
                    />
                    <TextInput
                        label={"Month:"}
                        style={{ width: "48%", backgroundColor: "rgba(0,0,0,0)" }}
                    //value={lastName}
                    //onChangeText={text => setLastName(text)}
                    />
                </View>
                <TextInput
                    label={i18n.t("message.localMinistry")}
                    style={{ backgroundColor: "rgba(0,0,0,0)" }}
                //value={lastName}
                //onChangeText={text => setLastName(text)}
                />
                <TextInput
                    label={i18n.t("message.country")}
                    style={{ backgroundColor: "rgba(0,0,0,0)" }}
                //value={lastName}
                //onChangeText={text => setLastName(text)}
                />
                <TextInput
                    label={i18n.t("message.ocupation")}
                    style={{ backgroundColor: "rgba(0,0,0,0)" }}
                //value={lastName}
                //onChangeText={text => setLastName(text)}
                />
                <Button mode="outlined" onPress={updateProfile}>{i18n.t("message.update")}</Button>
                */}
            </ImageBackground>
        </ScrollView>
    )
}

export default ProfileSettings;
