"use client";

import { useRouter } from 'next/navigation'
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import axios from "axios";


export default function Home() {
    const { data: session, status } = useSession();
    const [loaded, setLoaded] = useState(false)
    const router = useRouter()

    useEffect(() => {
        if (status == 'loading')
            return
        if (status != 'authenticated') {
            router.push('/settings/connections')
            return
        }
        if (loaded)
            return;

        const urlHash = window.location.hash
        if (!urlHash || !urlHash.startsWith('#')) {
            router.push('/settings/connections')
            return
        }
        const parts = urlHash.substring(1).split('&')
        const headers: { [key: string]: string } = {}
        parts.map(p => p.split('='))
            .forEach(p => headers[p[0]] = p[1])

        axios.post('/api/connection/authorize', {
            access_token: headers['access_token'],
            token_type: headers['token_type'],
            expires_in: headers['expires_in'],
            scope: headers['scope'],
            state: headers['state']
        })
            .then((d) => {
                router.push('/settings/connections')
            })
            .catch((d) => {
                if (d.response.data.message == 'Connection already saved.')
                    router.push('/settings/connections')
                else
                    setLoaded(true)
            })
    }, [session, status])

    return (
        <main>
            <div className="header">
                {loaded &&
                    <div className='text-center align-middle h-full'>
                        Something went wrong while saving the connection.
                    </div>
                }
            </div>
        </main>
    );
}