<script setup lang="ts">
import { router, useForm } from '@inertiajs/vue3';
import { Check, X } from '@lucide/vue';
import { 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 } from '@/types/cutting';

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

const { can } = useCan();

const rejectDialogOpen = ref(false);
const verifyDialogOpen = ref(false);
const allMatches = ref(true);

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

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

const verifyForm = useForm({
    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,
        })),
    }));
}

function submitVerify() {
    verifyForm
        .transform((data) => ({
            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/stocks/${props.cutting.id}/verify`, {
        preserveScroll: true,
        onSuccess: () => {
            verifyDialogOpen.value = false;
        },
        onError: (errors) => {
            const message = Object.values(errors)[0];

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

function submitReject() {
    rejectForm.post(`/admin/manage/stocks/${props.cutting.id}/reject`, {
        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();
    }
});
</script>

<template>
    <div class="flex flex-wrap items-center justify-end gap-1">
        <Tooltip v-if="can('cuttings.verify')">
            <TooltipTrigger as-child>
                <Button
                    size="sm"
                    variant="ghost"
                    class="text-green-600 hover:text-green-700"
                    @click="verifyDialogOpen = true"
                >
                    <Check class="size-3.5" />
                    <span class="sr-only">Verifikasi</span>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Verifikasi & Tambah Stok</TooltipContent>
        </Tooltip>

        <Tooltip v-if="can('cuttings.reject')">
            <TooltipTrigger as-child>
                <Button
                    size="sm"
                    variant="ghost"
                    class="text-destructive hover:text-destructive"
                    @click="rejectDialogOpen = true"
                >
                    <X class="size-3.5" />
                    <span class="sr-only">Tolak</span>
                </Button>
            </TooltipTrigger>
            <TooltipContent>Tolak Verifikasi</TooltipContent>
        </Tooltip>
    </div>

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

            <form @submit.prevent="submitReject">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="stock-reject-reason" required
                                >Alasan Penolakan</FieldLabel
                            >
                            <Textarea
                                id="stock-reject-reason"
                                v-model="rejectForm.reason"
                                placeholder="Contoh: Jumlah barang yang diterima tidak sesuai"
                                rows="3"
                                autofocus
                            />
                            <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. Stok akan ditambahkan setelah verifikasi.
                    </p>

                    <div class="flex items-center justify-between rounded-lg border p-3">
                        <Label for="stock-all-matches" class="text-sm font-medium">
                            Semua sesuai dengan data cutting
                        </Label>
                        <Switch
                            id="stock-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="`stock-good-${index}`" class="text-muted-foreground block mb-0.5">Stok Bagus (diterima):</label>
                                    <Input
                                        :id="`stock-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="`stock-reject-${index}`" class="text-muted-foreground block mb-0.5">Stok Reject (diterima):</label>
                                    <Input
                                        :id="`stock-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="`stock-price-${index}-${type}`">
                                        {{ PRICE_TYPE_LABELS[type] }}
                                    </FieldLabel>
                                    <RupiahInput
                                        :id="`stock-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="stock-verification-note">Catatan Verifikasi</FieldLabel>
                        <Textarea
                            id="stock-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 & Tambah Stok' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
