<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 type { EmployeeListItem } from '@/types/employee';

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

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

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

function toggleStatus(checked: boolean) {
    const previous = isActive.value;
    isActive.value = checked;
    processing.value = true;

    router.patch(`/admin/hr/employees/${props.employee.id}/toggle-status`, {
        is_active: checked,
    }, {
        preserveScroll: true,
        onError: () => {
            isActive.value = previous;
            toast.error('Gagal memperbarui status pegawai.');
        },
        onFinish: () => {
            processing.value = false;
        },
    });
}
</script>

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