<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 { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { useCan } from '@/composables/useCan';
import { RupiahInput } from '@/components/form/rupiah-input';
import { parseRupiah } from '@/lib/rupiah';
import {
    PRICE_TYPES,
    PRICE_TYPE_LABELS,
} from '@/types/product';
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 allMatches = ref(true);
const pendingAction = ref<CuttingStatusAction | null>(null);

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

function buildEmptyPrices(): Record<string, string> {
    return Object.fromEntries(PRICE_TYPES.map((type) => [type, '']));
}

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,
        original_warehouse_stock: res.warehouse_stock,
        original_cutting_reject: res.cutting_reject,
        prices: buildEmptyPrices(),
    })),
    result_prices: [] as Array<{
        product_variant_id: number;
        prices: Array<{ type: string; price: number }>;
    }>,
});

watch(verifyDialogOpen, (isOpen) => {
    if (isOpen) {
        allMatches.value = true;
        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,
            original_warehouse_stock: res.warehouse_stock,
            original_cutting_reject: res.cutting_reject,
            prices: buildEmptyPrices(),
        }));
        verifyForm.result_prices = [];
        verifyForm.clearErrors();
    }
});

watch(allMatches, (matches) => {
    if (!matches) {
        return;
    }

    verifyForm.results = verifyForm.results.map((result) => ({
        ...result,
        warehouse_stock: result.original_warehouse_stock,
        cutting_reject: result.original_cutting_reject,
    }));
});

function setAllMatches(value: boolean) {
    allMatches.value = value;

    if (value) {
        verifyForm.results = verifyForm.results.map((result) => ({
            ...result,
            warehouse_stock: result.original_warehouse_stock,
            cutting_reject: result.original_cutting_reject,
        }));
    }
}
function setResultPrice(resultIndex: number, type: string, value: string) {
    const result = verifyForm.results[resultIndex];
    if (!result) {
        return;
    }

    result.prices = {
        ...result.prices,
        [type]: value,
    };
}

function buildResultPricesPayload() {
    return verifyForm.results.map((result) => ({
        product_variant_id: result.product_variant_id,
        prices: PRICE_TYPES.map((type) => ({
            type,
            price: Number.parseInt(parseRupiah(result.prices[type] ?? ''), 10) || 0,
        })),
    }));
}

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. Stok bagus dan reject akan ditambahkan ke produk.';
    }

    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
        .transform((data) => ({
            status: data.status,
            verification_note: data.verification_note,
            results: data.results.map(({ product_variant_id, warehouse_stock, cutting_reject }) => ({
                product_variant_id,
                warehouse_stock,
                cutting_reject,
            })),
            result_prices: buildResultPricesPayload(),
        }))
        .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-2xl">
            <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">
                        Verifikasi jumlah produk yang diterima di toko dan tentukan harga jual per varian.
                    </p>

                    <div class="flex items-center justify-between rounded-lg border p-3">
                        <Label for="all-matches" class="text-sm font-medium">
                            Semua sesuai dengan data cutting
                        </Label>
                        <Switch
                            id="all-matches"
                            :model-value="allMatches"
                            @update:model-value="setAllMatches"
                        />
                    </div>

                    <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-3">
                            <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>
                                    <span class="text-muted-foreground block mb-0.5">Data cutting:</span>
                                    <span class="font-medium tabular-nums">
                                        {{ result.original_warehouse_stock }} bagus ·
                                        {{ result.original_cutting_reject }} reject
                                    </span>
                                </div>
                                <div>
                                    <span class="text-muted-foreground block">Stok Reject:</span>
                                    <Badge variant="secondary" class="font-semibold">
                                        {{ result.cutting_reject }} pcs
                                    </Badge>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-2 items-end text-xs">
                                <div>
                                    <label :for="`good-${index}`" class="text-muted-foreground block mb-0.5">Stok Bagus (diterima):</label>
                                    <Input
                                        :id="`good-${index}`"
                                        type="number"
                                        v-model.number="result.warehouse_stock"
                                        min="0"
                                        :max="result.cutting_result"
                                        class="h-8 w-full px-2 text-xs"
                                        :disabled="allMatches"
                                        @input="result.cutting_reject = result.cutting_result - result.warehouse_stock"
                                    />
                                </div>
                                <div>
                                    <label :for="`reject-${index}`" class="text-muted-foreground block mb-0.5">Stok Reject (diterima):</label>
                                    <Input
                                        :id="`reject-${index}`"
                                        type="number"
                                        v-model.number="result.cutting_reject"
                                        min="0"
                                        :max="result.cutting_result"
                                        class="h-8 w-full px-2 text-xs"
                                        :disabled="allMatches"
                                        @input="result.warehouse_stock = result.cutting_result - result.cutting_reject"
                                    />
                                </div>
                            </div>

                            <div class="grid gap-2 sm:grid-cols-2">
                                <Field v-for="type in PRICE_TYPES" :key="`${result.product_variant_id}-${type}`">
                                    <FieldLabel class="text-xs" :for="`price-${index}-${type}`">
                                        {{ PRICE_TYPE_LABELS[type] }}
                                    </FieldLabel>
                                    <RupiahInput
                                        :id="`price-${index}-${type}`"
                                        :model-value="result.prices[type]"
                                        @update:model-value="setResultPrice(index, type, $event)"
                                    />
                                </Field>
                            </div>
                        </div>
                    </div>

                    <FieldError
                        :errors="verifyForm.errors.result_prices ? [verifyForm.errors.result_prices] : []"
                    />

                    <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>
