import * as AuthSession from 'expo-auth-session';
import {TokenResponse} from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';
import React, {useEffect, useState} from 'react';
import {Button, Text, View} from "react-native";

WebBrowser.maybeCompleteAuthSession();
// const redirectURI = AuthSession.makeRedirectUri({native: 'http://127.0.0.1:8082/ssoCallback', // TODO: why is it translated to localhost? Why /ssoCallback is missing?});
const redirectURI = 'https://poc-sso-marn-500.van-hemmen.com/ssoCallback';

console.log(redirectURI);

export default function indexScreen() {
    const [tokenResponse, setTokenResponse] = useState<TokenResponse | null>(null);

    const clientId = '509-marn-poc-app';

    const discovery = AuthSession.useAutoDiscovery('https://auth-integ.partenamut.be/login/oauth2');

    const [request, result, promptAsync] = AuthSession.useAuthRequest(
        {
            clientId,
            redirectUri: redirectURI,
            usePKCE: true,
        },
        discovery,
    );

    useEffect(() => {
        console.log('result');
        console.log(result);
    }, [result]);

    useEffect(() => {
        console.log('request');
        console.log(request);
        request?.makeAuthUrlAsync(discovery!).then(value => console.log(value));
    }, [request]);

    useEffect(() => {
        console.log('tokenResponse');
        console.log(tokenResponse);
    }, [tokenResponse]);

    return (
        <View>
            <Text>HOME PAGE</Text>
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Button title="login SSO!" onPress={() => promptAsync()}/>
                <Button title="login SSO webtab!" onPress={() => WebBrowser.openBrowserAsync(request?.url)}/>
                <Button
                    title="redeem token"
                    onPress={async () => {
                        if (result && result.type === 'success') {
                            const exCode = await AuthSession.exchangeCodeAsync(
                                {
                                    clientId: '509-marn-app',
                                    redirectUri: redirectURI,
                                    code: result?.params?.code,
                                    extraParams: {
                                        code_verifier: request?.codeVerifier || '',
                                    },
                                },
                                {tokenEndpoint: discovery!.tokenEndpoint?.replace(':443', '')},
                            );

                            setTokenResponse(exCode);
                        }
                    }}
                />
                <Button
                    title="refresh token"
                    onPress={async () => {
                        if (tokenResponse) {
                            const exCode = await AuthSession.refreshAsync(
                                {
                                    clientId: '509-marn-app',
                                    refreshToken: tokenResponse.refreshToken,
                                },
                                {tokenEndpoint: discovery!.tokenEndpoint?.replace(':443', '')},
                            );
                            setTokenResponse(exCode);
                        }
                    }}
                />
                <Button
                    title="delete tokens"
                    onPress={async () => {
                        if (tokenResponse) {
                            const exCode = await AuthSession.revokeAsync(
                                {
                                    clientId,
                                    token: tokenResponse.accessToken!,
                                },
                                {revocationEndpoint: discovery!.revocationEndpoint?.replace(':443', '')},
                            );
                            const exCode2 = await AuthSession.revokeAsync(
                                {
                                    clientId,
                                    token: tokenResponse.refreshToken!,
                                },
                                {revocationEndpoint: discovery!.revocationEndpoint?.replace(':443', '')},
                            );
                            setTokenResponse(null);
                        }
                    }}
                />
                <Button
                    title="logout SSO?"
                    onPress={() => {
                        WebBrowser.openAuthSessionAsync(discovery!.endSessionEndpoint!, redirectURI);
                        // AuthSession.dismiss();
                        setTokenResponse(null);
                    }}
                />
                {request && (
                    <View style={{backgroundColor: 'green'}}>
                        <Text>{JSON.stringify(request, null, 2)}</Text>
                    </View>
                )}
                {result && (
                    <View style={{backgroundColor: 'coral'}}>
                        <Text>{JSON.stringify(result, null, 2)}</Text>
                    </View>
                )}
                {tokenResponse && (
                    <View style={{backgroundColor: 'pink'}}>
                        <Text>{JSON.stringify(tokenResponse, null, 2)}</Text>
                    </View>
                )}
            </View>
        </View>
    )
}
