<script setup lang="ts">
import { Link, router } from '@inertiajs/vue3';
import { Check, Pencil, Send, Trash2, X } from '@lucide/vue';
import { computed, ref } from 'vue';
import { toast } from 'vue-sonner';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useCan } from '@/composables/useCan';
import type { OrderListItem, OrderStatusAction } from '@/types/order';

const props = defineProps<{
    order: OrderListItem;
}>();

const { can } = useCan();

const deleteConfirmOpen = ref(false);
const deleteProcessing = ref(false);
const statusConfirmOpen = ref(false);
const statusProcessing = ref(false);
const pendingAction = ref<OrderStatusAction | null>(null);

const availableActions = computed(() => props.order.available_actions ?? []);

const canEdit = computed(() => props.order.is_editable && can('orders.update'));
const canDelete = computed(() => can('orders.delete'));

function canPerformAction(action: OrderStatusAction): boolean {
    return can(action.permission);
}

function statusConfirmDescription(action: OrderStatusAction): string {
    if (action.status === 'processing') {
        return `Pesanan ${props.order.order_number} akan dikirim dan diproses.`;
    }

    if (action.status === 'completed') {
        return `Pesanan ${props.order.order_number} akan ditandai selesai.`;
    }

    return `Pesanan ${props.order.order_number} akan dibatalkan. Stok produk akan dikembalikan.`;
}

function openStatusConfirm(action: OrderStatusAction) {
    pendingAction.value = action;
    statusConfirmOpen.value = true;
}

function transitionStatus() {
    if (!pendingAction.value) {
        return;
    }

    statusProcessing.value = true;

    router.post(`/admin/manage/orders/${props.order.id}/status`, {
        status: pendingAction.value.status,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            statusConfirmOpen.value = false;
            pendingAction.value = null;
        },
        onError: (errors) => {
            const message = Object.values(errors)[0];

            toast.error(typeof message === 'string' ? message : 'Gagal memperbarui status pesanan.');
        },
        onFinish: () => {
            statusProcessing.value = false;
        },
    });
}

function destroyOrder() {
    deleteProcessing.value = true;

    router.delete(`/admin/manage/orders/${props.order.id}`, {
        preserveScroll: true,
        onSuccess: () => {
            deleteConfirmOpen.value = false;
        },
        onError: () => {
            toast.error('Gagal menghapus pesanan.');
        },
        onFinish: () => {
            deleteProcessing.value = false;
        },
    });
}

function actionIcon(status: string) {
    if (status === 'processing') {
        return Send;
    }

    if (status === 'completed') {
        return Check;
    }

    return X;
}
</script>

<template>
    <div class="flex flex-wrap items-center justify-end gap-1">
        <template v-for="action in availableActions" :key="action.status">
            <Tooltip v-if="action.icon_only && canPerformAction(action)">
                <TooltipTrigger as-child>
                    <Button
                        variant="ghost"
                        size="icon"
                        class="size-8"
                        :class="action.destructive ? 'text-destructive hover:text-destructive' : ''"
                        @click="openStatusConfirm(action)"
                    >
                        <component :is="actionIcon(action.status)" class="size-4" />
                        <span class="sr-only">{{ action.label }}</span>
                    </Button>
                </TooltipTrigger>
                <TooltipContent>{{ action.label }}</TooltipContent>
            </Tooltip>

            <Button
                v-else-if="canPerformAction(action)"
                size="sm"
                :variant="action.destructive ? 'outline' : 'default'"
                :class="action.destructive ? 'text-destructive hover:text-destructive' : ''"
                @click="openStatusConfirm(action)"
            >
                <component :is="actionIcon(action.status)" class="size-3.5" />
                {{ action.label }}
            </Button>
        </template>

        <Tooltip v-if="canEdit">
            <TooltipTrigger as-child>
                <Button variant="ghost" size="icon" class="size-8" as-child>
                    <Link :href="`/admin/manage/orders/${order.id}/edit`">
                        <Pencil class="size-4" />
                        <span class="sr-only">Ubah</span>
                    </Link>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Ubah</TooltipContent>
        </Tooltip>

        <Tooltip v-if="canDelete">
            <TooltipTrigger as-child>
                <Button
                    variant="ghost"
                    size="icon"
                    class="text-destructive hover:text-destructive size-8"
                    @click="deleteConfirmOpen = true"
                >
                    <Trash2 class="size-4" />
                    <span class="sr-only">Hapus</span>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Hapus</TooltipContent>
        </Tooltip>
    </div>

    <ConfirmDialog
        v-model:open="statusConfirmOpen"
        :title="pendingAction ? `${pendingAction.label} pesanan?` : 'Ubah status pesanan?'"
        :description="pendingAction ? statusConfirmDescription(pendingAction) : ''"
        :confirm-label="pendingAction?.label ?? 'Konfirmasi'"
        cancel-label="Batal"
        :destructive="pendingAction?.destructive ?? false"
        :loading="statusProcessing"
        @confirm="transitionStatus"
    />

    <ConfirmDialog
        v-if="canDelete"
        v-model:open="deleteConfirmOpen"
        title="Hapus pesanan?"
        :description="`Pesanan ${order.order_number} akan dihapus.${order.is_editable ? ' Stok produk akan dikembalikan.' : ''}`"
        confirm-label="Hapus"
        cancel-label="Batal"
        destructive
        :loading="deleteProcessing"
        @confirm="destroyOrder"
    />
</template>
