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

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

const { can } = useCan();

function resolveIsActive(material: RawMaterialListItem): boolean {
    return material.display_is_active ?? material.is_active;
}

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

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

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

    if (checked === isActive.value) {
        return;
    }

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

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

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

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