<template>
    <div class="authorization">
        <div class="authorization__head">
            <FontAwesomeIcon class="authorization__head-link" icon="chevron-left" @click="goToMain()" />
            <div class="authorization__head-text" v-if="isLogin">Вход</div>
            <div class="authorization__head-text" v-else>Регистрация</div>
        </div>

        <div class="authorization__content" v-if="isLogin">
            <InputComp type="email" placeholder="Ваш email" :hasWarning="fieldHasErrors('Email')" v-model="dataLogin.email" />
            <InputComp type="password" placeholder="Пароль" :hasWarning="fieldHasErrors('Пароль')" v-model="dataLogin.password" />

            <ButtonComp class="authorization__button" value="Войти" type="primary" @click="submit()" />
            <div class="authorization__toggler">
                Ещё нет аккаунта?
                <span class="authorization__toggler-link" @click="toggleType()">Зарегистрироваться</span>
            </div>
        </div>

        <div class="authorization__content" v-else>
            <SwitchableImage class="authorization__photo" :value="dataRegister.image" :edited="true" @change="setRegisterImage" />
            <InputComp type="text" placeholder="Ваше имя *" :hasWarning="fieldHasErrors('Имя')" v-model="dataRegister.name" />
            <InputComp type="text" placeholder="Ваша фамилия *" :hasWarning="fieldHasErrors('Фамилия')" v-model="dataRegister.surname" />
            <InputComp type="email" placeholder="Ваш email *" :hasWarning="fieldHasErrors('Email')" v-model="dataRegister.email" />
            <InputComp type="password" placeholder="Пароль *" :hasWarning="fieldHasErrors('Пароль')" v-model="dataRegister.password" />
            <InputComp
                type="password"
                placeholder="Повторите пароль *"
                :hasWarning="fieldHasErrors('Пароль')"
                v-model="dataRegister.password2"
            />

            <ButtonComp class="authorization__button" value="Зарегистрироваться" type="primary" @click="submit()" />
            <div class="authorization__toggler">
                Уже есть аккаунт?
                <span class="authorization__toggler-link" @click="toggleType()">Войти</span>
            </div>
        </div>

        <NotificationsMain class="authorization__notifications" v-model="notifications" />
    </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import InputImage from "@/components/Authorization/InputImage.vue";
import NotificationsMain from "@/components/Notifications/NotificationsMain.vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store";
import { useUserApi } from "@/composables/api";
import { FieldsContainer, FieldChecks } from "@/modules/validator";
import { notification } from "@/types";
import SwitchableImage from "@/components/Common/SwitchableImage.vue";
import { convertFileToBase64String } from "@/composables/utils";
const router = useRouter();
const userStore = useUserStore();
const userApi = useUserApi();

const props = defineProps<{ type: string }>();

const isLogin = computed(() => props.type === "login");

function toggleType() {
    if (isLogin.value) {
        router.push("/register");
    } else {
        router.push("/login");
    }
    notifications.value = [];

    resetData();
}

function goToMain() {
    router.push("/");
}

//#region login and registration
const dataLogin = ref<{
    email: string;
    password: string;
}>({ email: "", password: "" });

const dataRegister = ref<{
    name: string;
    surname: string;
    email: string;
    password: string;
    password2: string;
    image: string;
    imageFile?: File;
}>({ name: "", surname: "", email: "", password: "", password2: "", image: "", imageFile: undefined });

async function setRegisterImage(file: File) {
    console.log(file);

    dataRegister.value.imageFile = file;
    dataRegister.value.image = await convertFileToBase64String(file);
}

const notifications = ref<notification[]>([]);

async function submit() {
    let errors = getFieldsErrors();

    notifications.value = errors;

    if (errors.length > 0) return;

    if (isLogin.value) {
        const resp = await userApi.login(dataLogin.value);
        userStore.setData(resp);
        router.push("/");
    } else {
        const resp = await userApi.register(dataRegister.value);
        notifications.value.push({ text: "Регистрация прошла успешно. Теперь вы можете войти.", type: "success" });
        router.push("/login");
    }

    resetData();
}

function getFieldsErrors() {
    const container = new FieldsContainer();
    if (isLogin.value) {
        container.addField("Email", dataLogin.value.email, [FieldChecks.nonEmpty, FieldChecks.email]);
        container.addField("Пароль", dataLogin.value.password, [FieldChecks.nonEmpty, FieldChecks.minLength(6), FieldChecks.maxLength(32)]);
    } else {
        container.addField("Имя", dataRegister.value.name, [
            FieldChecks.nonEmpty,
            FieldChecks.onlyLettersWhitespaces,
            FieldChecks.minLength(2),
            FieldChecks.maxLength(20),
        ]);
        container.addField("Фамилия", dataRegister.value.surname, [
            FieldChecks.nonEmpty,
            FieldChecks.onlyLettersWhitespaces,
            FieldChecks.minLength(2),
            FieldChecks.maxLength(20),
        ]);
        container.addField("Email", dataRegister.value.email, [FieldChecks.nonEmpty, FieldChecks.email]);
        container.addField("Пароль", dataRegister.value.password, [
            FieldChecks.nonEmpty,
            FieldChecks.minLength(6),
            FieldChecks.maxLength(32),
        ]);
    }

    let errors: notification[] = [];
    for (let [key, value] of container.fields) {
        const error = value.tryGetFirstError();
        if (error !== "") {
            errors.push({ field: key, text: error, type: "warning" });
        }
    }

    if (!isLogin.value) {
        if (dataRegister.value.password !== dataRegister.value.password2) {
            errors.push({ field: "Пароль", text: "Пароли не совпадают.", type: "warning" });
        }
    }
    return errors;
}

function fieldHasErrors(field: string) {
    return notifications.value.some((x) => x.field === field);
}

function resetData() {
    dataLogin.value = { email: "", password: "" };
    dataRegister.value = { name: "", surname: "", email: "", password: "", password2: "", image: "", imageFile: undefined };
}
//#endregion
</script>

<style lang="scss">
.authorization {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: r(40) r(70);

    &__head {
        display: flex;
        align-items: center;
        gap: r(20);
        font-size: r(20);
    }

    &__head-link {
        cursor: pointer;
    }

    &__content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    &__photo {
        align-self: center;
    }

    &__button {
        align-self: center;
        margin-top: r(30);
        min-width: 50%;
    }

    &__toggler {
        display: flex;
        justify-content: center;
        gap: r(5);
        margin-top: r(15);
        color: color("ui-background");
        font-size: r(19);
    }

    &__toggler-link {
        color: color("theme-color");
        cursor: pointer;
    }

    &__notifications {
        position: fixed;
        inset: auto 0 0 0;
    }
}
</style>
