<script setup lang="ts">
import { router, useForm } from '@inertiajs/vue3';
import { Check } from '@lucide/vue';
import { ref, watch } from 'vue';
import { toast } from 'vue-sonner';
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 { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
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 verifyDialogOpen = ref(false);
const allMatches = ref(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,
        warehouse_stock: res.warehouse_stock,
        cutting_reject: res.cutting_reject,
        original_warehouse_stock: res.warehouse_stock,
        original_cutting_reject: res.cutting_reject,
    })),
    variant_prices: [] as VariantPriceRow[],
    shared_prices: buildEmptyPrices(),
});

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,
        }));
        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();
    }
});

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 setSharedPrice(type: string, value: string) {
    verifyForm.shared_prices[type] = value;
    verifyForm.variant_prices = verifyForm.variant_prices.map((row) => ({
        ...row,
        prices: { ...row.prices, [type]: value },
    }));
}

function buildResultPricesPayload() {
    return verifyForm.variant_prices.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, 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.',
            );
        },
    });
}
</script>

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

    <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">
                        Verifikasi jumlah produk yang diterima dan tentukan harga jual. 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-2">
                        <div v-for="(result, index) in verifyForm.results" :key="result.product_variant_id" class="flex items-center gap-3 rounded-lg border p-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_warehouse_stock }} bagus, {{ result.original_cutting_reject }} reject)</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>
                                    <Input
                                        :id="`stock-good-${index}`"
                                        type="number"
                                        v-model.number="result.warehouse_stock"
                                        min="0"
                                        :max="result.cutting_result"
                                        class="h-7 w-16 px-1.5 text-xs text-center"
                                        :disabled="allMatches"
                                        @input="result.cutting_reject = result.cutting_result - result.warehouse_stock"
                                    />
                                </div>
                                <div class="text-center">
                                    <label :for="`stock-reject-${index}`" class="text-[10px] text-muted-foreground block">Reject</label>
                                    <Input
                                        :id="`stock-reject-${index}`"
                                        type="number"
                                        v-model.number="result.cutting_reject"
                                        min="0"
                                        :max="result.cutting_result"
                                        class="h-7 w-16 px-1.5 text-xs text-center"
                                        :disabled="allMatches"
                                        @input="result.warehouse_stock = result.cutting_result - result.cutting_reject"
                                    />
                                </div>
                            </div>
                        </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}`">
                                    {{ 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="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>
