/* 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 { makeRedirectUri } from "expo-auth-session";
import * as WebBrowser from 'expo-web-browser';
import { maybeCompleteAuthSession } from "expo-web-browser";
import React, { useState } from "react";
import { ActivityIndicator, Image, Pressable, StyleSheet, Text, TouchableHighlight, TouchableOpacity, View } from "react-native";
import { useAuth } from "../../data/Auth/AuthContext";
import { BaseStackNavigationProp } from "../../navigation/BaseStackNavigator";
import { API_URL } from "../../utils/RequestUtils";
import { GenericButton, PrimaryButton } from "../Buttons";
import UnauthorizedLayout from "./AuthLayout";
import { ProfileSectionHeader } from "./ProfileSections/ProfileSectionHeader";
import * as Linking from 'expo-linking';
import { BrowserLink, ProfileLegal } from "./ProfileSections/ProfileLegal";
import { Separator } from "../Separator";
import Collapsible from "react-native-collapsible";

/**
 * Props used by the {@link Intro} screen.
 */
export interface IntroProps {
    /**The {@link AuthStackNavigationProp} navigation object used to interact with the {@link Auth} navigator.*/
    navigation: BaseStackNavigationProp;
}

/**
 * Creates a browser session through which the user will login
 */
maybeCompleteAuthSession();

/**
 * The Intro screen displayed to unauthenticated users. Contains necessary methods to facilitate login and navigation to the [Registration]{@link RegisterMain} screens.
 * @component
 * @category Unauthorized
 */
const LoginView : React.FC<{navigation: BaseStackNavigationProp}> = ({navigation}) => {
    const {login} = useAuth()

    /**
     * @type {string} 
     * React state holding the login result message to display to the user.
     * */
    const loginMessageState = "";
    const [loginMessage, setLoginMessage] = useState<string>(loginMessageState);
    const [legalCollapsed, toggleLegal] = useState<boolean>(true)
    /**
     * @type {boolean} 
     * React state holding the error state of the component.
     * */
    const errorState = false;
    const [error, setError] = useState<boolean>(errorState);

    const redirectUri = makeRedirectUri({
        path: 'callback'
    });

    /**
     * Navigates to {@link RegisterMain}.
     */
    const goToRegistration = (): void => {
        console.log('[Navigation]: Navigating to registration page.')
        navigation.navigate("Register");
    }

    /**
     * Opens up the [privacy policy page]{@link https://app.clicknpush.ca/privacy}.
     */
    const openPrivacyPolicy = async () => {
        console.log('[Navigation]: Opening privacy policy.')
        await WebBrowser.openBrowserAsync(API_URL + "/privacy")
    }

    const openFeedback = () => {
        Linking.openURL('mailto:dev@clicknpush.ca')
    }

    const openLegal = () => {
        toggleLegal(!legalCollapsed)
    }

    return (
        <UnauthorizedLayout>
            {!loginMessage ?
            <View style={styles.introContainer}>
                <View style={styles.brandContainer}>
                    <Image resizeMode="contain" style={{height: 100}} source={require('../../../assets/logo-white.png')}></Image>
                </View>
                <View style={styles.btnContainer}>
                    <PrimaryButton text="Login" onPress={login}/>
                    <PrimaryButton text="Create account" onPress={goToRegistration} />
                    <View style={{width: '100%'}}>
                        <GenericButton text="Legal" style={{justifyContent: 'center', alignItems: 'center', padding: 20, width: '100%', }} onPress={openLegal}/>
                        <Separator color="#E0E0E0" />
                        <Collapsible collapsed={legalCollapsed} style={{borderColor: '#E0E0E0', borderBottomWidth: 1, borderRightWidth: 1, borderLeftWidth: 1, justifyContent: 'center', alignItems: 'center', padding: 20}} >
                            <BrowserLink style={{marginBottom: 20}} text="Mobile app third-party licenses" route="mobile-tpl"/>
                            <BrowserLink text="API third-party licenses" route="api-tpl"/>
                        </Collapsible>
                    </View>
                    <Separator color="#D3D3D3" />
                    <GenericButton text="Provide feedback" style={{justifyContent: 'center', alignItems: 'center', padding: 20, width: '100%', }} onPress={openFeedback}/>
                </View>
            </View> :
            <View style={{height: '100%', justifyContent: "center", alignItems: "center"}}>
                <Text style={{color: 'white', fontSize: 20, marginBottom: 30}}>{loginMessage}</Text>
                {!error ? <ActivityIndicator color='white' size="large"/> : <PrimaryButton text="Okay" onPress={() => {setError(false); setLoginMessage('')}}/> }
            </View> }
            <TouchableOpacity onPress={async () => await openPrivacyPolicy()}>
                <Text style={{fontSize: 12, textDecorationLine: "underline", alignSelf: "flex-end", color: 'white'}}>Privacy policy</Text>
            </TouchableOpacity>
        </UnauthorizedLayout>
    )
}

const styles = StyleSheet.create({
    introContainer: {
        alignItems: "center",
        justifyContent: 'flex-start'
    },
    brandContainer: {
        alignItems: "center",
    },
    title: {
        marginTop: 10, 
        color: 'white',
        fontSize: 20
    },
    btnContainer: {
        marginVertical: 20,
        padding: 20,
        backgroundColor: 'white',
        borderRadius: 10,
        alignItems: 'center',
        width: '100%',
        
    },
    registerBtn: {
        borderColor: 'white',
        borderWidth: 2,
        backgroundColor: 'transparent',
    }
})

export default LoginView;