<script setup lang="ts">
    import { computed, onMounted, nextTick, ref } from 'vue';
    import { storeToRefs } from 'pinia';
    import UIInput from '@/UI-kit/components/UI/inputs/UIInput.vue';
    import { EInputInputmode } from '@/UI-kit/types';
    import { useAuthStore, EAuthStep } from '@/modules/auth';
    import { useField, useForm } from 'vee-validate';
    import { buildYupChain } from '@/UI-kit/utils';
    import { string } from 'yup';
    import { requiredValueValidator } from '@/modules/documents/constants/validation/common.validation';
    import UIButton from '@/UI-kit/components/UI/button/UIButton.vue';
    import useRequestHandler from '@/UI-kit/composables/useRequestHandler';
    import type { IAuthApiMethods, IAuthSendEmailResponse } from '@/modules/auth/type/auth.type';

    interface Props {
        apiMethods?: IAuthApiMethods;
    }

    const props = defineProps<Props>();

    const authStore = useAuthStore();

    const { translates, authStep, userEmail } = storeToRefs(authStore);

    const isFormSubmitted = ref(false);

    const { handleSubmit, errors, setFieldError } = useForm({
        validationSchema: {
            email: buildYupChain(string(), [requiredValueValidator()]).email(
                translates.value.input.error,
            ),
        },
    });

    const { value: email } = useField<string>('email');

    const hasEmailError = computed(() => {
        if (!isFormSubmitted.value) {
            return false;
        }
        return !!errors.value.email;
    });

    const { requestHandler: sendEmail, isLoading: isLoadingAuthUserWithEmail } = useRequestHandler<
        string,
        IAuthSendEmailResponse
    >({
        request: async (emailValue: string) => {
            if (!props.apiMethods?.sendEmail) {
                throw new Error('API method sendEmail is not provided');
            }
            return props.apiMethods.sendEmail(emailValue);
        },
        then: async () => {
            userEmail.value = email.value || '';
            authStep.value = EAuthStep.confirm;
        },
    });

    const send = async () => {
        isFormSubmitted.value = true;
        await handleSubmit(() => {
            if (email.value) {
                sendEmail(email.value);
            }
        })();
    };

    const resetErrorState = (key: any) => {
        isFormSubmitted.value = false;
        setFieldError(key, '');
    };

    onMounted(() => {
        email.value = userEmail.value || '';
        nextTick(() => {
            resetErrorState('email');
        });
    });
</script>

<template>
    <div class="auth-form__inner">
        <div v-if="translates.title" class="auth-form__title" v-html="translates.title" />
        <div v-html="translates.input.description" />
        <UIInput
            v-model="email"
            placeholder="mail@yandex.ru"
            :label="translates.input.label"
            :inputmode="EInputInputmode.email"
            :error-message="errors.email"
            :is-error="hasEmailError"
            @update:model-value="resetErrorState('email')"
        />
        <UIButton
            :is-loading="isLoadingAuthUserWithEmail"
            :disabled="isLoadingAuthUserWithEmail"
            class="auth-form__btn"
            @click="send"
        >
            {{ translates.input.btn }}
        </UIButton>
    </div>
</template>

<style lang="scss" scoped>
    @use '@/UI-kit/assets/scss' as *;

    .auth-form {
        &__inner {
            @include text(14px, 500, 22px);
            @include flex(column, 16px);
        }

        &__title {
            @include text(18px, 700, 22px);
        }

        &__btn {
            @include text(14px, 500, 24px, var(--white));
            @include flex(row, 0, center, center);
        }
    }
</style>
