<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { computed, watch } from 'vue';
import { toast } from 'vue-sonner';
import { NumberInput } from '@/components/form/number-input';
import { RupiahInput } from '@/components/form/rupiah-input';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Field,
    FieldError,
    FieldLabel,
} from '@/components/ui/field';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { parseRupiah } from '@/lib/rupiah';
import { verify } from '@/routes/admin/manage/stocks';
import type { CuttingListItem } from '@/types/cutting';
import {
    PRICE_TYPES,
    PRICE_TYPE_LABELS,
} from '@/types/product';

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

const open = defineModel<boolean>('open', { required: true });

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

interface VariantPriceRow {
    product_variant_id: number;
    name: string;
    prices: Record<string, string>;
}

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,
        original_sample: res.sample,
        original_outside_sample: res.original_outside_sample,
        good: res.cutting_result,
        reject: 0,
    })),
    variant_prices: props.cutting.results.map(res => ({
        product_variant_id: res.product_variant?.id || 0,
        name: `${res.product_variant?.product?.name || ''} (${res.product_variant?.name || ''})`,
        prices: buildEmptyPrices(),
    })),
    shared_prices: buildEmptyPrices(),
});

watch(open, (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,
            original_sample: res.sample,
            original_outside_sample: res.original_outside_sample,
            good: res.cutting_result,
            reject: 0,
        }));
        verifyForm.variant_prices = props.cutting.results.map(res => ({
            product_variant_id: res.product_variant?.id || 0,
            name: `${res.product_variant?.product?.name || ''} (${res.product_variant?.name || ''})`,
            prices: buildEmptyPrices(),
        }));
        verifyForm.shared_prices = buildEmptyPrices();
        verifyForm.clearErrors();
    }
});

function onGoodChange(result: any, value: string | number) {
    const val = Number(value) || 0;
    result.good = val;
    result.reject = Math.max(0, result.cutting_result - val);
}

function onRejectChange(result: any, value: string | number) {
    const val = Number(value) || 0;
    result.reject = val;
    result.good = Math.max(0, result.cutting_result - val);
}

function setSharedPrice(type: string, value: string) {
    verifyForm.shared_prices[type] = value;
    verifyForm.variant_prices = verifyForm.variant_prices.map((row) => ({
        ...row,
        prices: { ...row.prices, [type]: value },
    }));
}

const resultPricesErrors = computed(() => {
    return Object.entries(verifyForm.errors)
        .filter(([key]) => key === 'result_prices' || key.startsWith('result_prices.'))
        .map(([_, message]) => message) as string[];
});

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

function submitVerify() {
    verifyForm
        .transform((data) => ({
            verification_note: data.verification_note,
            results: data.results.map(({ product_variant_id, good, reject }) => ({
                product_variant_id,
                good,
                reject,
            })),
            result_prices: buildResultPricesPayload(data.variant_prices),
        }))
        .post(verify.url(props.cutting.id), {
            preserveScroll: true,
            onSuccess: () => {
                open.value = false;
            },
            onError: (errors: Record<string, string>) => {
                const shown = new Set<string>();

                for (const [key, message] of Object.entries(errors)) {
                    if (
                        key === 'result_prices' ||
                        key.startsWith('result_prices.') ||
                        key.startsWith('results.') ||
                        key === 'verification_note'
                    ) {
                        continue;
                    }

                    if (!shown.has(message)) {
                        shown.add(message);
                        toast.error(message);
                    }
                }
            },
        });
}
</script>

<template>
    <Dialog v-model:open="open">
        <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">
                        Verifikasi jumlah produk yang diterima dan tentukan harga jual. Stok akan ditambahkan setelah
                        verifikasi.
                    </p>

                    <div class="space-y-2">
                        <div v-for="(result, index) in verifyForm.results" :key="result.product_variant_id"
                            class="flex flex-col gap-1 rounded-lg border p-3">
                            <div class="flex items-center gap-3">
                                <div class="flex-1 min-w-0">
                                    <p class="font-medium text-sm truncate">{{ result.name }}</p>
                                    <p class="text-xs text-muted-foreground">
                                        {{ result.cutting_result }} pcs
                                        <span class="text-[10px]">({{ result.original_sample }} Sample, {{
                                            result.original_outside_sample }} Diluar Sample)</span>
                                    </p>
                                </div>
                                <div class="flex items-center gap-2 shrink-0">
                                    <div class="text-center">
                                        <label :for="`stock-good-${index}`"
                                            class="text-[10px] text-muted-foreground block">Bagus</label>
                                        <NumberInput :id="`stock-good-${index}`" :model-value="result.good"
                                            class="h-7 w-20 px-1.5 text-xs text-center"
                                            @update:model-value="val => onGoodChange(result, val)" />
                                    </div>
                                    <div class="text-center">
                                        <label :for="`stock-reject-${index}`"
                                            class="text-[10px] text-muted-foreground block">Reject</label>
                                        <NumberInput :id="`stock-reject-${index}`" :model-value="result.reject"
                                            class="h-7 w-20 px-1.5 text-xs text-center"
                                            @update:model-value="val => onRejectChange(result, val)" />
                                    </div>
                                </div>
                            </div>
                            <FieldError :errors="[
                                verifyForm.errors[`results.${index}.good`],
                                verifyForm.errors[`results.${index}.reject`],
                                verifyForm.errors[`results.${index}.product_variant_id`]
                            ].filter(Boolean) as string[]" />
                        </div>
                    </div>

                    <Separator />

                    <div class="space-y-2">
                        <p class="text-sm font-medium">Harga</p>
                        <div class="grid gap-2 sm:grid-cols-2">
                            <Field v-for="type in PRICE_TYPES" :key="`shared-${type}`">
                                <FieldLabel class="text-xs" :for="`shared-price-${type}`" required>
                                    {{ PRICE_TYPE_LABELS[type] }}
                                </FieldLabel>
                                <RupiahInput :id="`shared-price-${type}`" :model-value="verifyForm.shared_prices[type]"
                                    @update:model-value="setSharedPrice(type, $event)" />
                            </Field>
                        </div>
                    </div>

                    <FieldError :errors="resultPricesErrors" />

                    <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="open = false">
                        Batal
                    </Button>
                    <Button type="submit" :disabled="verifyForm.processing">
                        {{ verifyForm.processing ? 'Menyimpan...' : 'Verifikasi & Tambah Stok' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
