<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { ref, watch } from 'vue';
import { toast } from 'vue-sonner';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { useCan } from '@/composables/useCan';
import { toggle_status } from '@/routes/admin/hr/employees';
import type { EmployeeListItem } from '@/types/employee';

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

const { can } = useCan();

const isActive = ref(props.employee.is_active);
const processing = ref(false);

watch(
    () => props.employee.is_active,
    (value) => {
        isActive.value = value;
    },
);

function toggleStatus(checked: boolean) {
    if (!can('employees.toggle_status')) {
        return;
    }

    const previous = isActive.value;
    isActive.value = checked;
    processing.value = true;

    router.patch(toggle_status.url(props.employee.id), {
        is_active: checked,
    }, {
        preserveScroll: true,
        onError: (errors: any) => {
            isActive.value = previous;

            if (errors.system) {
                toast.error(errors.system);
            }
        },
        onFinish: () => {
            processing.value = false;
        },
    });
}
</script>

<template>
    <div class="flex items-center gap-2">
        <Switch :model-value="isActive" :disabled="processing || !can('employees.toggle_status')"
            @update:model-value="toggleStatus" />
        <Badge :variant="isActive ? 'default' : 'secondary'">
            {{ isActive ? 'Aktif' : 'Nonaktif' }}
        </Badge>
    </div>
</template>
