<script setup lang="ts">
import { router } from '@inertiajs/vue3';
import { computed, 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 { ProductStatus } from '@/constants/active-status';
import { toggle_status } from '@/routes/admin/master/products';
import type { ProductListItem } from '@/types/product';

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

const { can } = useCan();

function resolveStatus(product: ProductListItem): string {
    return product.display_status ?? product.status;
}

const currentStatus = ref(resolveStatus(props.product));
const processing = ref(false);

const isActive = computed(() => currentStatus.value === ProductStatus.ACTIVE);
const isDraft = computed(() => currentStatus.value === ProductStatus.DRAFT);

watch(
    () => resolveStatus(props.product),
    (value) => {
        currentStatus.value = value;
    },
);

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

    const newStatus = checked ? ProductStatus.ACTIVE : ProductStatus.INACTIVE;

    if (newStatus === currentStatus.value) {
        return;
    }

    processing.value = true;
    currentStatus.value = newStatus;

    router.patch(toggle_status.url(props.product.id), {
        status: newStatus,
    }, {
        preserveScroll: true,
        onError: (errors: any) => {
            currentStatus.value = resolveStatus(props.product);

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

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

<template>
    <div class="flex items-center gap-2">
        <template v-if="isDraft">
            <Badge variant="secondary">Draf</Badge>
        </template>
        <template v-else>
            <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>
        </template>
    </div>
</template>
