<template>
    <v-card width="100%" :disabled="loading || processingPassword" :loading="loading || processingPassword">
        <v-toolbar density="compact">
            <v-row no-gutters class="pa-3 text-h6 font-weight-bold">
                <span>{{ promptTitle }}</span>
            </v-row>
        </v-toolbar>
        <v-card-text style="max-height: 100vh; overflow-y: auto" class="pa-5 my-5 px-7 text-center">
            <v-row no-gutters class="w-100">
                <v-col cols="12">
                    <v-icon icon="mdi-lock-outline" :color="'gray'" class="text-h2" />
                </v-col>
                <v-col cols="12" v-if="message" class="mt-2">
                    {{ message }}
                </v-col>
                <v-col cols="12" class="mt-5 text-start">
                    <v-text-field v-model="passwordInput" label="Password" type="password" density="compact" :error-messages="errorMessage"></v-text-field>
                </v-col>
            </v-row>
        </v-card-text>

        <v-toolbar class="pa-0" density="compact">
            <v-row no-gutters>
                <v-col cols="6" class="pa-0">
                    <v-btn block variant="text" class="text-none" size="large" tile @click="emit('cancel')" height="48">
                        Cancel
                    </v-btn>
                </v-col>

                <v-col cols="6" class="pa-0">
                    <v-btn block tile variant="flat" class="text-none" size="large" height="48" color="red" :disabled="!passwordInput"
                        @click="handleConfirm">
                        Confirm
                    </v-btn>
                </v-col>
            </v-row>
        </v-toolbar>
    </v-card>
</template>

<script setup lang="ts">

const props = defineProps({
    message: {
        type: String,
        default: "Confirm your digital signature with password to proceed."
    },
    promptTitle: {
        type: String,
        default: "Confirm Action"
    },
    loading: {
        type: Boolean,
        default: false
    },
})

const { confirmPassword } = useDOBEntries();
const { currentUser } = useLocalAuth();

const emit = defineEmits(["cancel", "confirm"])

const processingPassword = ref(false)
const errorMessage = ref('')


const passwordInput = ref('')



async function handleConfirm() {
    errorMessage.value = ''
  try {
    processingPassword.value = true;
    const userId = currentUser.value?._id;
    if (!userId) {
        throw new Error('User not found. Please login again.');
    }   
    const res = await confirmPassword({ userId, password: passwordInput.value });
    if (res) {
      emit('confirm');
    }

  } catch (err: any) {
    const errMessage = err?.response?._data?.message || 'Something went wrong. Please try again.';
    console.log('[ERROR]', err)
    errorMessage.value = errMessage;
  } finally {
    processingPassword.value = false;
  }
}

</script>

<style scoped></style>