<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { watch } from 'vue';
import { toast } from 'vue-sonner';
import { RupiahInput } from '@/components/form/rupiah-input';
import MediaThumbnailCell from '@/components/media/MediaThumbnailCell.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,
    FieldLabel,
} from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { CuttingStatus } from '@/constants/cutting-status';
import { parseRupiah } from '@/lib/rupiah';
import { transition_status } from '@/routes/admin/manage/cuttings';
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, '']));
}

const verifyForm = useForm({
    status: CuttingStatus.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,
        sample: res.sample,
        original_outside_sample: res.original_outside_sample,
        original_sample: res.sample,
        original_original_outside_sample: res.original_outside_sample,
        prices: buildEmptyPrices(),
    })),
    result_prices: [] as Array<{
        product_variant_id: number;
        prices: Array<{ type: string; price: number }>;
    }>,
});

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,
            sample: res.sample,
            original_outside_sample: res.original_outside_sample,
            original_sample: res.sample,
            original_original_outside_sample: res.original_outside_sample,
            prices: buildEmptyPrices(),
        }));
        verifyForm.result_prices = [];
        verifyForm.clearErrors();
    }
});

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) => ({
            status: data.status,
            verification_note: data.verification_note,
            results: data.results.map(({ product_variant_id, sample, original_outside_sample }) => ({
                product_variant_id,
                sample,
                original_outside_sample,
            })),
            result_prices: buildResultPricesPayload(),
        }))
        .post(transition_status.url(props.cutting.id), {
            preserveScroll: true,
            onSuccess: () => {
                open.value = false;
            },
            onError: (errors: Record<string, string>) => {
                if (errors.system) {
                    toast.error(errors.system);
                }
            },
        });
}
</script>

<template>
    <Dialog v-model:open="open">
        <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="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_sample }} Sample ·
                                        {{ result.original_original_outside_sample }} Diluar Sample
                                    </span>
                                </div>
                                <div>
                                    <span class="text-muted-foreground block">Diluar Sample:</span>
                                    <Badge variant="secondary" class="font-semibold">
                                        {{ result.original_outside_sample }} pcs
                                    </Badge>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-2 items-end text-xs">
                                <div>
                                    <label :for="`sample-${index}`" class="text-muted-foreground block mb-0.5">Sample
                                        (diterima):</label>
                                    <Input :id="`sample-${index}`" type="number" v-model.number="result.sample" min="0"
                                        :max="result.cutting_result" class="h-8 w-full px-2 text-xs"
                                        @input="result.original_outside_sample = result.cutting_result - result.sample" />
                                </div>
                                <div>
                                    <label :for="`diluar-sample-${index}`"
                                        class="text-muted-foreground block mb-0.5">Diluar
                                        Sample
                                        (diterima):</label>
                                    <Input :id="`diluar-sample-${index}`" type="number"
                                        v-model.number="result.original_outside_sample" min="0"
                                        :max="result.cutting_result" class="h-8 w-full px-2 text-xs"
                                        @input="result.sample = result.cutting_result - result.original_outside_sample" />
                                </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}`" required>
                                        {{ 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>

                    <div v-if="cutting.materials && cutting.materials.length > 0" class="space-y-2 mt-4">
                        <p class="text-sm font-medium">Bahan Baku Terpakai</p>
                        <div class="grid gap-2">
                            <div v-for="material in cutting.materials" :key="material.id"
                                class="flex items-center gap-3 rounded-lg border p-3 bg-muted/10">
                                <div class="shrink-0">
                                    <MediaThumbnailCell :items="material.raw_material_price?.images ?? []" :max-visible="1" />
                                </div>
                                <div class="flex-1 min-w-0">
                                    <p class="font-medium text-sm truncate">
                                        {{ material.raw_material_name || material.raw_material_price?.raw_material?.name }} - {{ material.variant || material.raw_material_price?.variant }}
                                    </p>
                                    <p class="text-xs text-muted-foreground">
                                        Pemakaian: {{ material.material_usage_formatted }}
                                        <span v-if="material.combination_id" class="text-[10px] text-primary bg-primary/10 px-1.5 py-0.5 rounded ml-2 font-medium">Kombinasi</span>
                                    </p>
                                </div>
                            </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="Masukkan catatan verifikasi" 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' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
