/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written and maintained by the Click & Push Development team 
 * <dev@clicknpush.ca>, January 2022
 */

import axios from 'axios';
import { ImageInfo } from 'expo-image-picker/build/ImagePicker.types';
import * as WebBrowser from 'expo-web-browser';
import { observer } from "mobx-react";
import React, { useEffect, useState } from "react";
import { ActivityIndicator, Alert, AppState, Button, Image, ImageBackground, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { renderers } from 'react-native-popup-menu';
import { API_URL, reportAxiosError } from '../../utils/RequestUtils';
import { PhotoPicker } from '../PhotoPicker';
import { ProfileHeader } from "./ProfileHeader";
import { ProfileSections } from "./ProfileSections";
import { PrivacyLink } from '../PrivacyLink';
import { ProfileMainStyles } from "./Styles/Profile.styles";
import { useAuth } from '../../data/Auth/AuthContext';
import { BaseStackNavigationProp } from '../../navigation/BaseStackNavigator';
import { useChangePassword, useDeleteProfile, useEditProfile, useOwnedProfile, useToggleTips } from '../../data/profiles';
const {SlideInMenu} = renderers

/**
 * The screen component that displays the user's profile. Gets user information from the {@link useProfile} hook.
 * @component
 */
const Profile: React.FC = () => {
    const {userId, accessToken} = useAuth()
    const [changingPassword, toggleChangingPassword] = useState<boolean>(false) 
    const [photoSourceMenuOpened, togglePhotoSourceMenu] = useState<boolean>(false)
    const [newPhotoB64, setNewPhoto] = useState<string>()
    const [loadingImg, setLoadingImg] = useState<boolean>(false)
    const [uploadingImg, setUploadingImg] = useState<boolean>(false)
    
    const {profile} = useOwnedProfile()
    const editProfileMutation = useEditProfile()
    const changePasswordMutation = useChangePassword()
    const toggleTipsMutation = useToggleTips()
    const deleteAccountMutation = useDeleteProfile()

    useEffect(() => {
        if (newPhotoB64) {
            Alert.alert("Confirm new picture", "Are you sure you want to change your profile picture?", 
                [
                    {text: 'Yes', onPress: async () => await uploadPhoto()},
                    {text: 'No', onPress: cancelNewPhoto}
                ])   
            }
    }, [newPhotoB64])

    const initiateNewPhotoSelect = async () => {
        togglePhotoSourceMenu(false)
        setLoadingImg(true)
    }

    const onPhotoSelected = async (result: ImageInfo) => {
        setNewPhoto(result.base64)
        setLoadingImg(false)
    }

    const uploadPhoto = async () => {
        setUploadingImg(true)
        let photoData = new FormData()
        photoData.append('profPic', 'data:image/png;base64,' + newPhotoB64);

        try {
            const response = await axios({
              method: 'post',
              url: API_URL + '/api/user-profile/change-picture/' + userId + '/',
              headers: { "Authorization": "Bearer " + accessToken, },
              timeout: 50000,
              data: photoData,
            });
    
            if (response.status == 200) {
                Alert.alert("You successfully changed your profile picture!")
                setUploadingImg(false)
            }
            
        } catch (error) {
            reportAxiosError("[ProfileData]: Something went wrong when changing a profile picture", error, true)
            Alert.alert("Something went wrong when changing your profile picture.")
        }
    }

    const cancelNewPhoto = () => {
        togglePhotoSourceMenu(false)
        setLoadingImg(false)
        setNewPhoto('')
    }
    const LogoutButton: React.FC = () => {
        const {logout} = useAuth()

        return (
            <TouchableOpacity style={ProfileMainStyles.logoutButtonContainer} onPress={async () => await logout()}>
                <Text style={ProfileMainStyles.logoutButtonText}>Logout</Text>
            </TouchableOpacity>
        )
    }

    return (
        <>
            <ScrollView contentContainerStyle={{justifyContent: "flex-end", alignItems: 'center', padding: 10}}>
                    {loadingImg || uploadingImg ?
                    <View style={{marginVertical: 30}}>
                        <Text style={{color: 'white', fontSize: 20, marginBottom: 10}}>{
                            loadingImg ? 'Loading image...' :
                            uploadingImg ? 'Uploading image' : null }
                        </Text>
                        <ActivityIndicator color='white' size="large"/> 
                    </View> :
                    <ImageBackground style={ProfileMainStyles.profileImage} source={newPhotoB64 ? {uri: 'data:image/png;base64,' + newPhotoB64} : profile?.image_b64 ? {uri: 'data:image/png;base64,' + profile?.image_b64} : require('../../../assets/default-pfp.png')}>
                        <TouchableOpacity style={{width: "100%", height: "100%", zIndex: 12}} onPress={() => togglePhotoSourceMenu(true)} >
                            <View style={ProfileMainStyles.profileImageOverlay}>
                                <Text style={{fontSize: 12, textAlign: 'center', color: 'white', opacity: 1}}>Change profile picture</Text>
                            </View>
                        </TouchableOpacity>
                    </ImageBackground> }
                    
                    <View style={ProfileMainStyles.profileSubContainer}>
                        <Text style={ProfileMainStyles.headerUsername}>{profile?.username}</Text>
                        <ProfileHeader profile={profile} />
                        <ProfileSections 
                            resetChangeInfo={editProfileMutation.reset}
                            changeInfo={editProfileMutation.mutateAsync}
                            changeInfoStatus={editProfileMutation.status}
                            resetChangePassword={changePasswordMutation.reset}
                            changePasswordStatus={changePasswordMutation.status} 
                            deleteAccount={deleteAccountMutation.mutateAsync}
                            deleteAccountStatus={deleteAccountMutation.status}
                            profile={profile} 
                            toggleTipsAsync={toggleTipsMutation.mutateAsync} 
                            changePassword={changePasswordMutation.mutateAsync} />
                        <LogoutButton />
                        <PrivacyLink />
                    </View>
                </ScrollView>
                <PhotoPicker multiple={false} menuType='alert' cancel={cancelNewPhoto} photoSourceMenuOpened={photoSourceMenuOpened} onBeforeLaunchPicker={initiateNewPhotoSelect} onReceivedPhotoResult={result => onPhotoSelected(result)} />
            </>            
    )
}

export default observer(Profile)
