<script setup lang="ts">
import { Link, router, useForm } from '@inertiajs/vue3';
import { Check, Pencil, RotateCcw, Scissors, Trash2, X } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { toast } from 'vue-sonner';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { useCan } from '@/composables/useCan';
import { FIELD_LIMITS } from '@/lib/field-limits';
import type { CuttingListItem, CuttingStatusAction } from '@/types/cutting';

const props = defineProps<{
    cutting: CuttingListItem;
}>();

const { can } = useCan();

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

const rejectForm = useForm({
    status: 'rejected',
    reason: '',
});

const verifyForm = useForm({
    status: 'verified',
    verification_note: '',
    results: props.cutting.results.map(res => ({
        product_variant_id: res.product_variant?.id || 0,
        name: `${res.product_variant?.product?.name || ''} (${res.product_variant?.name || ''})`,
        cutting_result: res.cutting_result,
        warehouse_stock: res.warehouse_stock,
        cutting_reject: res.cutting_reject,
    })),
});

watch(verifyDialogOpen, (isOpen) => {
    if (isOpen) {
        verifyForm.verification_note = '';
        verifyForm.results = props.cutting.results.map(res => ({
            product_variant_id: res.product_variant?.id || 0,
            name: `${res.product_variant?.product?.name || ''} (${res.product_variant?.name || ''})`,
            cutting_result: res.cutting_result,
            warehouse_stock: res.warehouse_stock,
            cutting_reject: res.cutting_reject,
        }));
        verifyForm.clearErrors();
    }
});

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

const canEdit = computed(
    () => props.cutting.is_editable && can('cuttings.update'),
);
const canDelete = computed(
    () => can('cuttings.delete') && ['in_progress', 'rejected'].includes(props.cutting.status),
);

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

function statusConfirmDescription(action: CuttingStatusAction): string {
    if (action.status === 'completed') {
        return 'Cutting akan ditandai selesai. Stok bahan baku akan dipotong dan sisa dikembalikan. Menunggu verifikasi admin toko.';
    }

    if (action.status === 'verified') {
        return 'Hasil cutting akan diverifikasi dan stok produk gudang akan ditambahkan.';
    }

    if (action.status === 'in_progress') {
        return 'Cutting dikembalikan ke proses untuk diperbaiki.';
    }

    return '';
}

function openStatusConfirm(action: CuttingStatusAction) {
    if (action.status === 'verified') {
        verifyDialogOpen.value = true;

        return;
    }

    if (action.status === 'rejected') {
        rejectForm.reset();
        rejectForm.clearErrors();
        rejectDialogOpen.value = true;

        return;
    }

    pendingAction.value = action;
    statusConfirmOpen.value = true;
}

function submitVerify() {
    verifyForm.post(`/admin/manage/cuttings/${props.cutting.id}/status`, {
        preserveScroll: true,
        onSuccess: () => {
            verifyDialogOpen.value = false;
        },
        onError: (errors) => {
            const message = Object.values(errors)[0];

            toast.error(
                typeof message === 'string'
                    ? message
                    : 'Gagal memverifikasi cutting.',
            );
        },
    });
}

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

    statusProcessing.value = true;

    router.post(
        `/admin/manage/cuttings/${props.cutting.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 cutting.',
                );
            },
            onFinish: () => {
                statusProcessing.value = false;
            },
        },
    );
}

function submitReject() {
    rejectForm.post(`/admin/manage/cuttings/${props.cutting.id}/status`, {
        preserveScroll: true,
        onSuccess: () => {
            rejectDialogOpen.value = false;
        },
        onError: (errors) => {
            const message = Object.values(errors)[0];

            toast.error(
                typeof message === 'string'
                    ? message
                    : 'Gagal menolak cutting.',
            );
        },
    });
}

watch(rejectDialogOpen, (isOpen) => {
    if (!isOpen) {
        rejectForm.reset();
        rejectForm.clearErrors();
    }
});

function destroyCutting() {
    deleteProcessing.value = true;

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

function actionIcon(status: string) {
    if (status === 'completed') {
        return Scissors;
    }

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

    if (status === 'in_progress') {
        return RotateCcw;
    }

    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="canPerformAction(action)">
                <TooltipTrigger as-child>
                    <Button
                        size="sm"
                        variant="ghost"
                        :class="
                            action.destructive
                                ? 'text-destructive hover:text-destructive'
                                : ''
                        "
                        @click="openStatusConfirm(action)"
                    >
                        <component
                            :is="actionIcon(action.status)"
                            class="size-3.5"
                        />
                        <span class="sr-only">{{ action.label }}</span>
                    </Button>
                </TooltipTrigger>

                <TooltipContent>
                    {{ action.label }}
                </TooltipContent>
            </Tooltip>
        </template>

        <Tooltip v-if="canEdit">
            <TooltipTrigger as-child>
                <Button variant="ghost" size="icon" class="size-8" as-child>
                    <Link :href="`/admin/manage/cuttings/${cutting.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="size-8 text-destructive hover:text-destructive"
                    @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} cutting?`
                : 'Ubah status cutting?'
        "
        :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 cutting?"
        description="Data cutting ini akan dihapus permanen."
        confirm-label="Hapus"
        cancel-label="Batal"
        destructive
        :loading="deleteProcessing"
        @confirm="destroyCutting"
    />

    <Dialog v-model:open="rejectDialogOpen">
        <DialogContent class="sm:max-w-md">
            <DialogHeader>
                <DialogTitle>Tolak Cutting</DialogTitle>
            </DialogHeader>

            <form @submit.prevent="submitReject">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="cutting-reject-reason" required
                                >Alasan Penolakan</FieldLabel
                            >
                            <Textarea
                                id="cutting-reject-reason"
                                v-model="rejectForm.reason"
                                placeholder="Contoh: Jumlah barang yang diterima tidak sesuai"
                                rows="3"
                                autofocus
                                :maxlength="FIELD_LIMITS.reason"
                            />
                            <FieldError
                                :errors="
                                    rejectForm.errors.reason
                                        ? [rejectForm.errors.reason]
                                        : []
                                "
                            />
                        </Field>
                    </FieldSet>
                </FieldGroup>

                <DialogFooter class="mt-6">
                    <Button
                        type="button"
                        variant="outline"
                        :disabled="rejectForm.processing"
                        @click="rejectDialogOpen = false"
                    >
                        Batal
                    </Button>
                    <Button
                        type="submit"
                        variant="destructive"
                        :disabled="rejectForm.processing"
                    >
                        {{ rejectForm.processing ? 'Menyimpan...' : 'Tolak' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>

    <Dialog v-model:open="verifyDialogOpen">
        <DialogContent class="sm:max-w-lg">
            <DialogHeader>
                <DialogTitle>Verifikasi Hasil Cutting</DialogTitle>
            </DialogHeader>

            <form @submit.prevent="submitVerify">
                <div class="space-y-4 max-h-[60vh] overflow-y-auto scrollbar-thin px-1 py-1">
                    <p class="text-sm text-muted-foreground">
                        Silakan verifikasi jumlah produk yang diterima di toko. Jika terdapat perbedaan/selisih, jumlah produk masuk gudang akan disesuaikan secara otomatis dan selisihnya akan dicatat sebagai reject.
                    </p>

                    <div class="space-y-3">
                        <div v-for="(result, index) in verifyForm.results" :key="result.product_variant_id" class="p-3 border rounded-lg space-y-2">
                            <div class="font-medium text-sm">
                                {{ result.name }}
                            </div>
                            <div class="grid grid-cols-3 gap-2 items-center text-xs">
                                <div>
                                    <span class="text-muted-foreground block">Hasil Potong:</span>
                                    <span class="font-semibold">{{ result.cutting_result }} pcs</span>
                                </div>
                                <div>
                                    <label :for="`received-${index}`" class="text-muted-foreground block mb-0.5">Diterima:</label>
                                    <Input
                                        :id="`received-${index}`"
                                        type="number"
                                        v-model.number="result.warehouse_stock"
                                        min="0"
                                        :max="result.cutting_result"
                                        class="h-8 w-20 px-2 text-xs"
                                        @input="result.cutting_reject = result.cutting_result - result.warehouse_stock"
                                    />
                                </div>
                                <div>
                                    <span class="text-muted-foreground block">Selisih (Reject):</span>
                                    <Badge variant="secondary" class="font-semibold">
                                        {{ result.cutting_reject }} pcs
                                    </Badge>
                                </div>
                            </div>
                        </div>
                    </div>

                    <Field>
                        <FieldLabel for="verification-note">Catatan Verifikasi</FieldLabel>
                        <Textarea
                            id="verification-note"
                            v-model="verifyForm.verification_note"
                            placeholder="Contoh: Terdapat 1 barang cacat jahitan saat dihitung di toko"
                            rows="3"
                        />
                        <FieldError
                            :errors="verifyForm.errors.verification_note ? [verifyForm.errors.verification_note] : []"
                        />
                    </Field>
                </div>

                <DialogFooter class="mt-6">
                    <Button
                        type="button"
                        variant="outline"
                        :disabled="verifyForm.processing"
                        @click="verifyDialogOpen = false"
                    >
                        Batal
                    </Button>
                    <Button
                        type="submit"
                        :disabled="verifyForm.processing"
                    >
                        {{ verifyForm.processing ? 'Menyimpan...' : 'Verifikasi' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
