import React from "react";
import { styled } from "styled-components";
import { HashLoader } from "react-spinners";
import { SigninResponse, UserManager } from 'oidc-client-ts';
import { User } from "../../API/User";
import FloatingBox from "../../components/UI/FloatingBox";

import constants from "../../constants";

const CenterContainer = styled.div`
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    text-align: center;

    & h2 {
        font-size: 1.8em;
        font-weight: 600;
        margin: 1.5em 0;
    }
`;

const ErrorText = styled.p`
    font-family: monospace;
    margin: 10px 0;
    width: 780px;
`;

export default class LoggedIn extends React.Component {
    constructor(props) {
        super(props);
        this.response = new SigninResponse(new URL(window.location.href).searchParams);
    }

    async componentDidMount() {
        if (this.response.error) return;
        window.localStorage.removeItem('auth_fail');

        let code_verifier = '?';
        // get code verifier
        for (const key in localStorage) {
            if (key.startsWith('oidc.')) {
                code_verifier = JSON.parse(localStorage[key]).code_verifier;
                localStorage.removeItem(key);
                break;
            }
        }

        const response = await User.login({...this.response, code_verifier});

        if (response.error) {
            // pass the data to LoginPage
            window.localStorage.setItem('auth_fail', JSON.stringify(response));
            window.location.href = '/login';
            return;
        }

        if (response.new_user) {
            // TODO: Make the page
            window.location.href = '/register';
        } else {
            window.location.href = '/';
        }
    }

    render() {
        return (
            <>
                <div style={{height: '65vh'}}>
                    <CenterContainer>
                        <h2>Подождите пожалуйста</h2>
                        <div style={{margin: '36px auto', width:'fit-content'}}>
                            <HashLoader size='80px' color='#0077aa' />
                        </div>
                    </CenterContainer>
                </div>
                
                {
                    this.response.error ?
                    <div>
                        <FloatingBox>
                            <h2>Ошибка авторизации</h2>
                            <p>{this.response.error}</p>
                            <ErrorText>{this.response.error_description}</ErrorText>
                        </FloatingBox>
                    </div>
                    : null
                }
            </>
        )
    }
}