<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 type { RawMaterialListItem } from '@/types/raw-material';

const props = defineProps<{
    material: RawMaterialListItem;
}>();

const { can } = useCan();

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

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

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

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

    router.patch(`/admin/master/raw-materials/${props.material.id}/toggle-status`, {
        is_active: checked,
    }, {
        preserveScroll: true,
        onError: () => {
            isActive.value = previous;
            toast.error('Gagal memperbarui status bahan baku.');
        },
        onFinish: () => {
            processing.value = false;
        },
    });
}
</script>

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