<template>
    <div class="col-xl-12">
        <UserFormInput
            title="아이디"
            name="id"
            :is-alert="idAlert"
            :is-essential="true"
            :useInputGroup="true"
            @update:data="handleIdChange"
            :value="id"
            :disabled="resetForm"
        />
        <template v-if="!resetForm">
            <UserFormInput
                title="생년월일"
                name="birth"
                :type="'date'"
                :is-essential="true"
                :is-alert="birthAlert"
                @update:data="birth = $event"
                @update:alert="birthAlert = $event"
                :value="birth"
            />
            <FormSelect
                title="비밀번호 힌트"
                name="pwhint"
                :is-essential="true"
                :is-row="false"
                :is-label="true"
                :is-common="true"
                :data="pwhintList"
                @update:data="pwhint = $event"
            />
            <UserFormInput
                title="답변"
                name="pwhintRes"
                :is-essential="true"
                :is-alert="pwhintResAlert"
                @update:data="pwhintRes = $event"
                @update:alert="pwhintResAlert = $event"
                :value="pwhintRes"
            />
            <div class="d-flex mt-5">
                <RouterLink type="button" class="btn btn-secondary me-2 w-50" to="/login">취소</RouterLink>
                <button type="button" @click="handleSubmit" class="btn btn-primary w-50">확인</button>
            </div>
        </template>
    </div>

    <div v-if="resetForm" class="mt-4">
        <UserFormInput
            title="새 비밀번호"
            name="pw"
            type="password"
            :isEssential="true"
            :is-alert="passwordAlert"
            @update:data="password = $event"
            @update:alert="passwordAlert = $event"
            :value="password"
        />

        <UserFormInput
            title="비밀번호 확인"
            name="pwch"
            type="password"
            :isEssential="true"
            :is-alert="passwordcheckAlert"
            @update:data="passwordcheck = $event"
            @update:alert="passwordcheckAlert = $event"
            @blur="checkPw"
            :value="passwordcheck"
        />
        <span v-if="passwordcheckError" class="invalid-feedback d-block">{{ passwordcheckError }}</span>

        <div class="d-grid gap-2 mt-5 mb-5">
            <button type="button" @click="handleNewPassword" class="btn btn-primary">확인</button>
        </div>
    </div>
</template>

<script setup>
    import { ref } from 'vue';
    import $api from '@api';
    import commonApi from '@/common/commonApi';
    import { useRouter } from 'vue-router';
    import { useToastStore } from '@s/toastStore';
    import UserFormInput from '@c/input/UserFormInput.vue';
    import FormSelect from '../input/FormSelect.vue';

    const router = useRouter();
    const toastStore = useToastStore();

    const id = ref('');
    const birth = ref('');
    const pwhint = ref('');
    const pwhintRes = ref('');

    const idAlert = ref(false);
    const birthAlert = ref(false);
    const pwhintResAlert = ref(false);
    const resetForm = ref(false);

    const password = ref('');
    const passwordcheck = ref('');
    const passwordcheckError = ref('');

    const passwordAlert = ref(false);
    const passwordcheckAlert = ref(false);
    const passwordcheckErrorAlert = ref(false);

    const { pwhintList } = commonApi();

    const handleIdChange = value => {
        id.value = value;
        idAlert.value = false;
    };

    // 아이디, 생년월일, 비밀번호 힌트, 답변이 일치하는 member 재설정 input 보이기
    const handleSubmit = async () => {
        idAlert.value = id.value.trim() === '';
        pwhintResAlert.value = pwhintRes.value.trim() === '';
        birthAlert.value = birth.value.trim() === '';

        if (idAlert.value || pwhintResAlert.value || birthAlert.value) {
            return;
        }

        const response = await $api.post('user/pwReset', {
            id: id.value,
            birth: birth.value,
            pwhint: pwhint.value,
            pwhintRes: pwhintRes.value,
        });

        if (response.status === 200 && response.data.data === true) {
            resetForm.value = true;
        } else {
            toastStore.onToast('일치하는 정보가 없습니다.', 'e');
        }
    };

    const checkPw = async () => {
        if (password.value !== passwordcheck.value) {
            passwordcheckError.value = '비밀번호가 일치하지 않습니다.';
            passwordcheckErrorAlert.value = true;
        } else {
            passwordcheckError.value = '';
            passwordcheckErrorAlert.value = false;
        }
    };

    // 비밀번호 업데이트
    const handleNewPassword = async () => {
        passwordAlert.value = password.value.trim() === '';
        passwordcheckAlert.value = passwordcheck.value.trim() === '';

        if (passwordAlert.value || passwordcheckAlert.value || passwordcheckErrorAlert.value) {
            return;
        }

        const checkResponse = await $api.post('user/checkPassword', {
            id: id.value,
            password: password.value
        });

        if (checkResponse.data.data === false) {
            toastStore.onToast('기존 비밀번호와 동일한 비밀번호로 변경할 수 없습니다.', 'e');
            return;
        }

        const response = await $api.patch('user/pwNew', {
            id: id.value,
            password: password.value
        });

        if (response.status === 200 && response.data.data === true) {
            toastStore.onToast('비밀번호가 재설정 되었습니다.', 's');
            router.push('/login');
        }

    };
</script>
