<script setup lang="ts">
import { router, usePage } from '@inertiajs/vue3';
import { KeyRound } from '@lucide/vue';
import { ref } from 'vue';
import { toast } from 'vue-sonner';
import { RowDeleteAction, RowEditAction, RowStatusAction } from '@/components/button';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { useCan } from '@/composables/useCan';
import { edit, destroy, reset_password } from '@/routes/admin/hr/employees';
import type { EmployeeListItem } from '@/types/employee';

const props = defineProps<{
    employee: EmployeeListItem;
}>();

const { can } = useCan();
const page = usePage();
const defaultPassword = page.props.auth.password_default as string;

const resetPasswordConfirmOpen = ref(false);
const resetPasswordProcessing = ref(false);

function resetPassword() {
    resetPasswordProcessing.value = true;

    router.post(reset_password.url(props.employee.id), {}, {
        preserveScroll: true,
        onSuccess: () => {
            resetPasswordConfirmOpen.value = false;
        },
        onError: (errors: any) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
        onFinish: () => {
            resetPasswordProcessing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center justify-end gap-1">
        <RowEditAction v-if="can('employees.update')" :href="edit.url(employee.id)" />

        <RowStatusAction v-if="can('employees.reset_password')" :icon="KeyRound" label="Reset Kata Sandi"
            @click="resetPasswordConfirmOpen = true" />

        <RowDeleteAction v-if="can('employees.delete')" :action-url="destroy.url(employee.id)" title="Hapus pegawai?"
            :description="`Data pegawai ${employee.profile?.full_name ?? ''} akan dihapus secara permanen beserta akun pengguna terkait. Tindakan ini tidak dapat dibatalkan.`"
            error-message="Gagal menghapus pegawai." />
    </div>

    <ConfirmDialog v-if="can('employees.reset_password')" v-model:open="resetPasswordConfirmOpen"
        title="Reset kata sandi pegawai?"
        :description="`Kata sandi ${employee.profile?.full_name ?? 'pegawai'} akan direset ke kata sandi default sistem (${defaultPassword}). Pengguna akan otomatis logout dari semua sesi aktif.`"
        confirm-label="Reset Kata Sandi" cancel-label="Batal" :loading="resetPasswordProcessing"
        @confirm="resetPassword" />
</template>
