import { makeAutoObservable } from "mobx";
import { LoginPageService } from "./LoginPageService";
import { createStandaloneToast } from "@chakra-ui/react";
import { error } from "../../utils/ToastHelper";
import { IOauthQueryParams } from "./types";



export class LoginPageStore {
    toast = createStandaloneToast();
    login: string = "";
    password: string = "";
    isLoading: boolean = false;

    private getQueryParams(): IOauthQueryParams | null {
        const url = window.location.href;
        const urlObj = new URL(url);
        const params = new URLSearchParams(urlObj.search);

        const redirectUri: string | null = params.get('redirect_to');
        const state: string | null = params.get('state');

        if (state && redirectUri) return { redirectUri: redirectUri, state: state }
        return null;
    }

    setLogin(value: string) {
        this.login = value;
    }

    setPassword(value: string) {
        this.password = value;
        LoginPageService.login
    }

    async handleLogin() {
        const oauthParams = this.getQueryParams()

        if (oauthParams) await this.loginAsOauth(oauthParams);
        else await this.loginSimpleWay()
    }

    async loginAsOauth(oauthParams: IOauthQueryParams) {
        this.isLoading = true;

        const result = await LoginPageService
            .loginOauth({
                password: this.password,
                username: this.login,
                redirectUri: oauthParams.redirectUri,
                state: oauthParams.state
            });
        this.isLoading = false;

        if (result?.isError) {
            error("Ошибка", "Запрос не был выполнен")
            return;
        }

        if (result && !result.loggedIn) {
            error("Неверный логин или пароль", "Проверьте еще раз")
            return;
        }

        window.location.replace(result.href!);

    }


    async loginSimpleWay() {

        this.isLoading = true;

        const result = await LoginPageService.login({ password: this.password, username: this.login })
        this.isLoading = false;

        if (result.isError) {
            error("Ошибка", "Запрос не был выполнен")
            return;
        }

        if (!result.loggedIn) {
            error("Неверный логин или пароль", "Проверьте еще раз")
            return;
        }

        window.location.replace("https://localhost:5173");
    }



    constructor() {
        makeAutoObservable(this);
    }


}


