<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/products';
import type { ProductListItem } from '@/types/product';

const props = defineProps<{
    product: ProductListItem;
}>();

const { can } = useCan();

function resolveIsActive(product: ProductListItem): boolean {
    return product.display_is_active ?? product.is_active;
}

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

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

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

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

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

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

            if (errors.system) {
                toast.error(errors.system);
            }

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

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