import {Component, ElementRef, HostListener, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AlertController, IonInput, LoadingController, ModalController, PopoverController} from '@ionic/angular';
import {EditorService} from '../../service/editor.service';
import {ApiService} from '../../service/api.service';
import {NavigationService} from '../../service/navigation.service';
import {AuthService} from '../../service/auth.service';
import {environment} from '../../../environments/environment';

export type LoginPageStep = 'greeter' | 'username' | 'password' | 'create-account';

@Component({
    selector: 'app-login',
    templateUrl: './login.page.html',
    styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
    public step: LoginPageStep = 'greeter';
    @ViewChild('usernameInput') usernameInput: IonInput;
    @ViewChild('passwordInput') passwordInput: IonInput;
    @ViewChild('nameInput') nameInput: IonInput;

    stepMessages = {
        username: 'Enter a username to continue',
        password: 'Enter your password to sign-in',
        'create-account': 'Welcome! Create an account to continue',
    };

    public username = '';
    public password = '';
    public fullName = '';
    public passwordConfirm = '';
    public userExists?: boolean;
    public userInfo: any = {};
    public errorMessage = '';

    public readonly logoUrl = environment.logoUrl;

    public readonly coreidUrl: string;

    constructor(
        protected api: ApiService,
        protected route: ActivatedRoute,
        protected router: Router,
        protected loader: LoadingController,
        protected popover: PopoverController,
        protected alerts: AlertController,
        protected modals: ModalController,
        public readonly editorService: EditorService,
        public readonly navService: NavigationService,
        public readonly auth: AuthService,
    ) {
        this.coreidUrl = this.api._build_url(environment.starshipUrl, '/');
    }

    ngOnInit() {}

    async ionViewDidEnter() {

    }

    coreid() {
        window.location.assign(this.coreidUrl);
    }

    async back() {
        this.errorMessage = '';

        if ( this.step === 'password' ) {
            this.password = '';
            this.step = 'username';

            setTimeout(() => {
                if ( this.usernameInput ) {
                    this.usernameInput.setFocus();
                }
            }, 150);
        } else if ( this.step === 'create-account' ) {
            this.fullName = '';
            this.password = '';
            this.passwordConfirm = '';
            this.step = 'username';

            setTimeout(() => {
                if ( this.usernameInput ) {
                    this.usernameInput.setFocus();
                }
            }, 150);
        }
    }

    async advance() {
        this.errorMessage = '';

        if ( this.step === 'greeter' ) {
            this.step = 'username';

            setTimeout(() => {
                if ( this.usernameInput ) {
                    this.usernameInput.setFocus();
                }
            }, 150);
        } else if ( this.step === 'username' ) {
            if ( !this.username ) {
                return;
            }

            const loader = await this.loader.create({ message: 'Checking username...' });
            await loader.present();

            this.userInfo = await this.api.getUserInfo(this.username);
            this.userExists = !!this.userInfo?.exists;
            if ( this.userExists ) {
                this.step = 'password';

                setTimeout(() => {
                    if ( this.passwordInput ) {
                        this.passwordInput.setFocus();
                    }
                }, 150);
            } else {
                this.step = 'create-account';

                setTimeout(() => {
                    if ( this.nameInput ) {
                        this.nameInput.setFocus();
                    }
                }, 150);
            }

            await loader.dismiss();
        } else if ( this.step === 'password' ) {
            if ( !this.username || !this.password ) {
                return;
            }

            const loader = await this.loader.create({ message: 'Signing you in...' });
            await loader.present();

            const result = await this.api.attemptLogin(this.username, this.password);
            await loader.dismiss();

            if ( !result.success ) {
                this.errorMessage = result.message || 'Un unknown error has occurred';
            } else {
                this.auth.authInProgress = true;
                this.navService.requestInitialization();
                this.reset();
            }
        } else if ( this.step === 'create-account' ) {
            if ( !this.username || !this.password || this.passwordConfirm !== this.password || !this.fullName ) {
                return;
            }

            const loader = await this.loader.create({ message: 'Creating your account...' });
            await loader.present();

            const result = await this.api.attemptRegistration(this.username, this.password, this.passwordConfirm, this.fullName);
            await loader.dismiss();

            if ( !result.success ) {
                this.errorMessage = result.message || 'Un unknown error has occurred';
            } else {
                this.auth.authInProgress = true;
                this.navService.requestInitialization();
                this.reset();
            }
        }
    }

    reset() {
        this.username = '';
        this.password = '';
        this.passwordConfirm = '';
        this.fullName = '';
        this.step = 'greeter';
    }
}
