<script setup lang="ts">
import { computed } from 'vue';
import { Head } from '@inertiajs/vue3';
import { Printer, X, FileText } from 'lucide-vue-next';

interface Modifier {
    name: string;
    price: number;
}

interface TransactionItem {
    id: number;
    qty: number;
    variant: string | null;
    price: number;
    subtotal: number;
    product: {
        id: number;
        name: string;
    } | null;
    modifiers: Modifier[];
}

interface TransactionDetail {
    id: number;
    transaction_number: string;
    total_amount: number;
    tax_amount: number;
    service_charge_amount: number;
    discount_amount: number;
    payment_method: string;
    status: 'success' | 'cancelled';
    created_at: string;
    order_type: string;
    queue_number: string | null;
    table: {
        id: number;
        number: string;
    } | null;
    customer: {
        id: number;
        name: string;
    } | null;
    outlet: {
        id: number;
        name: string;
    } | null;
    user: {
        id: number;
        name: string;
    } | null;
    items: TransactionItem[];
}

const props = defineProps<{
    transaction: TransactionDetail;
    appName: string;
    thermalLogo: string;
}>();

// Get cash parameters dynamically from query string (if available)
const urlParams = new URLSearchParams(window.location.search);
const cashReceivedQuery = urlParams.get('cash_received');
const changeQuery = urlParams.get('change');

const cashReceived = computed(() => cashReceivedQuery ? parseFloat(cashReceivedQuery) : null);
const changeDue = computed(() => changeQuery ? parseFloat(changeQuery) : null);
const isRaw = computed(() => urlParams.get('raw') === 'true');

const printDateTime = computed(() => {
    const now = new Date();
    return now.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }) + ' ' +
           now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
});

const formatCurrency = (val: number) => {
    return 'Rp ' + new Intl.NumberFormat('id-ID').format(Math.round(val));
};

const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('id-ID', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    });
};

const paymentLabel = (method: string) => {
    const map: Record<string, string> = { cash: 'Tunai (Cash)', transfer: 'Transfer Bank', qris: 'QRIS' };
    return map[method] ?? method;
};

const triggerPrint = () => {
    window.print();
};

const closeWindow = () => {
    window.close();
};
</script>

<template>
    <Head :title="'Cetak Struk - ' + transaction.transaction_number" />

    <!-- Raw content version for QZ Tray silent print -->
    <div v-if="isRaw" class="w-[58mm] text-black font-mono leading-tight p-0 m-0 bg-white" style="zoom: 0.8; transform-origin: top left; max-width: 58mm;">
        <!-- Brand Header & Logo -->
        <div class="space-y-1 text-black text-center flex flex-col items-center justify-center w-full">
            <img 
                v-if="thermalLogo" 
                :src="thermalLogo" 
                alt="Logo" 
                class="max-h-14 max-w-full object-contain mb-1 block border-0 bg-transparent mx-auto"
            />
            <div class="font-extrabold text-[15px] tracking-widest uppercase text-center w-full">
                {{ appName }}
            </div>
            <div class="text-[11px] font-bold uppercase tracking-wide text-center w-full">
                {{ transaction.outlet?.name || 'CafePOS Store' }}
            </div>
            <div class="text-[10px] font-medium leading-tight text-center w-full pb-2">
                Bukti Pembayaran POS
            </div>
        </div>

        <!-- Meta Info Block -->
        <div class="border-t border-b border-dashed border-black py-2.5 space-y-1 text-[11px] leading-relaxed text-black">
            <div class="flex justify-between">
                <span>No.:</span>
                <span class="font-bold">{{ transaction.transaction_number }}</span>
            </div>
            <div class="flex justify-between">
                <span>Tanggal:</span>
                <span class="font-bold">{{ formatDate(transaction.created_at) }}</span>
            </div>
            <div class="flex justify-between">
                <span>Kasir:</span>
                <span class="font-bold">{{ transaction.user?.name || '-' }}</span>
            </div>
            <div class="flex justify-between" v-if="transaction.table">
                <span>Meja (Table):</span>
                <span class="font-bold">Meja {{ transaction.table.number }}</span>
            </div>
            <div class="flex justify-between" v-if="transaction.customer">
                <span>Pelanggan:</span>
                <span class="font-bold">{{ transaction.customer.name }}</span>
            </div>
            <div class="flex justify-between">
                <span>Tipe:</span>
                <span class="font-bold uppercase">
                    {{ transaction.order_type ? transaction.order_type.replace('_', ' ') : 'POS' }}
                </span>
            </div>
            <div class="flex justify-between">
                <span>Status:</span>
                <span class="font-bold uppercase">
                    {{ transaction.status === 'success' ? 'AKTUAL' : 'VOIDED' }}
                </span>
            </div>
            <div class="flex justify-between" v-if="transaction.queue_number">
                <span>No. Antrean:</span>
                <span class="font-bold text-[12px] border border-black text-black px-1.5 rounded">{{ transaction.queue_number }}</span>
            </div>
        </div>

        <!-- Section: Items list -->
        <div class="space-y-3 py-1 text-black">
            <div v-for="item in transaction.items" :key="item.id" class="space-y-1">
                <div class="font-bold text-[11px] leading-tight text-left">
                    {{ item.product?.name || 'Unknown Item' }}
                </div>
                <div class="flex justify-between text-[10px] pl-3 leading-normal font-bold">
                    <span>
                        {{ item.qty }} x {{ formatCurrency(item.price) }}
                        <span v-if="item.variant" class="font-bold uppercase ml-1.5">[{{ item.variant }}]</span>
                    </span>
                    <span class="flex-shrink-0 ml-2 font-bold">{{ formatCurrency(item.subtotal) }}</span>
                </div>
                <div v-if="item.modifiers && item.modifiers.length > 0" class="pl-5 text-[9.5px] leading-normal italic font-medium">
                    <div v-for="m in item.modifiers" :key="m.name" class="flex justify-between">
                        <span>+ {{ m.name }}</span>
                        <span v-if="m.price > 0" class="flex-shrink-0 ml-2">{{ formatCurrency(m.price) }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pricing Summary -->
        <div class="space-y-1.5 text-[11px] border-t border-dashed border-black pt-3 text-black">
            <div class="flex justify-between">
                <span>Subtotal:</span>
                <span>{{ formatCurrency(transaction.total_amount - transaction.tax_amount - transaction.service_charge_amount + transaction.discount_amount) }}</span>
            </div>
            <div class="flex justify-between" v-if="transaction.discount_amount > 0">
                <span>Diskon (Promo):</span>
                <span>-{{ formatCurrency(transaction.discount_amount) }}</span>
            </div>
            <div class="flex justify-between" v-if="transaction.service_charge_amount > 0">
                <span>Service Charge:</span>
                <span>{{ formatCurrency(transaction.service_charge_amount) }}</span>
            </div>
            <div class="flex justify-between" v-if="transaction.tax_amount > 0">
                <span>Pajak (Tax):</span>
                <span>{{ formatCurrency(transaction.tax_amount) }}</span>
            </div>
            
            <div class="border-t border-double border-black my-2"></div>
            
            <div class="flex justify-between text-[11px] font-black uppercase">
                <span>TOTAL KESELURUHAN:</span>
                <span>{{ formatCurrency(transaction.total_amount) }}</span>
            </div>
            
            <div class="border-t border-dashed border-black my-2"></div>
            
            <div class="flex justify-between">
                <span>Metode Pembayaran:</span>
                <span class="font-bold uppercase">{{ paymentLabel(transaction.payment_method) }}</span>
            </div>
            
            <template v-if="transaction.payment_method === 'cash'">
                <div class="flex justify-between" v-if="cashReceived !== null">
                    <span>Tunai Diterima:</span>
                    <span>{{ formatCurrency(cashReceived) }}</span>
                </div>
                <div class="flex justify-between font-bold" v-if="changeDue !== null">
                    <span>Kembalian:</span>
                    <span>{{ formatCurrency(changeDue) }}</span>
                </div>
            </template>
        </div>

        <!-- Receipt Footer -->
        <div class="text-center space-y-1.5 text-[10px] pt-4 border-t border-dashed border-black mt-4 text-black font-mono">
            <p class="font-extrabold text-[11px] uppercase tracking-wider">TERIMA KASIH</p>
            <p>Atas Kunjungan & Pembelian Anda</p>
            <p class="italic text-[9.5px]">"Fresh Coffee, Warm Vibes."</p>
            <div class="border-t border-dotted border-black my-2 w-1/2 mx-auto"></div>
            <p class="text-[9px]">Sistem POS: {{ appName }}</p>
            <p class="text-[8.5px]">Waktu Cetak: {{ printDateTime }}</p>
        </div>
    </div>

    <!-- Normal preview page for browser print -->
    <div v-else class="min-h-screen bg-slate-900 text-slate-800 font-sans flex flex-col items-center print:bg-white print:text-black">
        <!-- Top Action Bar (Hidden on Print) -->
        <div class="w-full bg-slate-950 border-b border-slate-800 px-6 py-4 flex items-center justify-between shadow-md print:hidden select-none sticky top-0 z-50">
            <div class="flex items-center gap-2.5">
                <div class="p-2 bg-red-600/10 rounded-xl">
                    <FileText class="h-5 w-5 text-red-500" />
                </div>
                <div>
                    <h1 class="text-sm font-bold text-slate-100 flex items-center gap-1.5">
                        Cetak Struk POS
                        <span class="text-[9px] px-1.5 py-0.5 rounded bg-red-600 text-white font-bold uppercase tracking-wider">Receipt 80mm</span>
                    </h1>
                    <p class="text-[10px] text-slate-400 mt-0.5">Struk Transaksi: {{ transaction.transaction_number }}</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <button
                    @click="triggerPrint"
                    class="px-4 py-2 bg-red-600 hover:bg-red-500 text-white rounded-xl text-xs font-bold transition-all cursor-pointer flex items-center gap-2 shadow-lg shadow-red-950/20 active:scale-95 animate-pulse"
                >
                    <Printer class="h-4 w-4" />
                    <span>Cetak Struk</span>
                </button>
                <button
                    @click="closeWindow"
                    class="px-4 py-2 bg-slate-850 hover:bg-slate-800 border border-slate-700 text-slate-300 rounded-xl text-xs font-bold transition-all cursor-pointer flex items-center gap-2 active:scale-95"
                >
                    <X class="h-4 w-4" />
                    <span>Tutup</span>
                </button>
            </div>
        </div>

        <!-- Receipt Wrapper for realistic screen view -->
        <div class="my-8 print:my-0 flex justify-center w-full print:justify-start">
            <main class="w-[58mm] min-h-[100mm] bg-white text-black p-4 shadow-2xl relative border-t-8 border-red-600 print:shadow-none print:border-t-0 print:p-0 print:w-[58mm] print:m-0">

                <!-- Receipt Body Content -->
                <div class="space-y-4 font-mono text-black">
                    <!-- Brand Header & Logo -->
                    <div class="space-y-1 text-black text-center flex flex-col items-center justify-center w-full">
                        <img 
                            v-if="thermalLogo" 
                            :src="thermalLogo" 
                            alt="Logo" 
                            class="max-h-14 max-w-full object-contain mb-1 block border-0 bg-transparent mx-auto"
                        />
                        <div class="font-extrabold text-[15px] tracking-widest uppercase text-center w-full">
                            {{ appName }}
                        </div>
                        <div class="text-[11px] font-bold uppercase tracking-wide text-center w-full">
                            {{ transaction.outlet?.name || 'CafePOS Store' }}
                        </div>
                        <div class="text-[10px] font-medium leading-tight text-center w-full pb-2">
                            Bukti Pembayaran POS
                        </div>
                    </div>

                    <!-- Meta Info Block -->
                    <div class="border-t border-b border-dashed border-black py-2.5 space-y-1 text-[11px] leading-relaxed text-black">
                        <div class="flex justify-between">
                            <span>No.:</span>
                            <span class="font-bold">{{ transaction.transaction_number }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Tanggal:</span>
                            <span class="font-bold">{{ formatDate(transaction.created_at) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Kasir:</span>
                            <span class="font-bold">{{ transaction.user?.name || '-' }}</span>
                        </div>
                        <div class="flex justify-between" v-if="transaction.table">
                            <span>Meja (Table):</span>
                            <span class="font-bold">Meja {{ transaction.table.number }}</span>
                        </div>
                        <div class="flex justify-between" v-if="transaction.customer">
                            <span>Pelanggan:</span>
                            <span class="font-bold">{{ transaction.customer.name }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Tipe:</span>
                            <span class="font-bold uppercase">
                                {{ transaction.order_type ? transaction.order_type.replace('_', ' ') : 'POS' }}
                            </span>
                        </div>
                        <div class="flex justify-between">
                            <span>Status:</span>
                            <span class="font-bold uppercase">
                                {{ transaction.status === 'success' ? 'AKTUAL' : 'VOIDED' }}
                            </span>
                        </div>
                        <div class="flex justify-between" v-if="transaction.queue_number">
                            <span>No. Antrean:</span>
                            <span class="font-bold text-[12px] border border-black text-black px-1.5 rounded">{{ transaction.queue_number }}</span>
                        </div>
                    </div>

                    <!-- Section: Items list -->
                    <div class="space-y-3 py-1 text-black">
                        <div v-for="item in transaction.items" :key="item.id" class="space-y-1">
                            <!-- Line 1: Item Name (Can wrap safely) -->
                            <div class="font-bold text-[11px] leading-tight text-left">
                                {{ item.product?.name || 'Unknown Item' }}
                            </div>
                            <!-- Line 2: Qty x Unit Price, Variant, and Item Subtotal aligned -->
                            <div class="flex justify-between text-[10px] pl-3 leading-normal font-bold">
                                <span>
                                    {{ item.qty }} x {{ formatCurrency(item.price) }}
                                    <span v-if="item.variant" class="font-bold uppercase ml-1.5">[{{ item.variant }}]</span>
                                </span>
                                <span class="flex-shrink-0 ml-2 font-bold">{{ formatCurrency(item.subtotal) }}</span>
                            </div>
                            <!-- Line 3: Modifiers (Add-ons) -->
                            <div v-if="item.modifiers && item.modifiers.length > 0" class="pl-5 text-[9.5px] leading-normal italic font-medium">
                                <div v-for="m in item.modifiers" :key="m.name" class="flex justify-between">
                                    <span>+ {{ m.name }}</span>
                                    <span v-if="m.price > 0" class="flex-shrink-0 ml-2">{{ formatCurrency(m.price) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pricing Summary -->
                    <div class="space-y-1.5 text-[11px] border-t border-dashed border-black pt-3 text-black">
                        <div class="flex justify-between">
                            <span>Subtotal:</span>
                            <span>{{ formatCurrency(transaction.total_amount - transaction.tax_amount - transaction.service_charge_amount + transaction.discount_amount) }}</span>
                        </div>
                        <div class="flex justify-between" v-if="transaction.discount_amount > 0">
                            <span>Diskon (Promo):</span>
                            <span>-{{ formatCurrency(transaction.discount_amount) }}</span>
                        </div>
                        <div class="flex justify-between" v-if="transaction.service_charge_amount > 0">
                            <span>Service Charge:</span>
                            <span>{{ formatCurrency(transaction.service_charge_amount) }}</span>
                        </div>
                        <div class="flex justify-between" v-if="transaction.tax_amount > 0">
                            <span>Pajak (Tax):</span>
                            <span>{{ formatCurrency(transaction.tax_amount) }}</span>
                        </div>
                        
                        <div class="border-t border-double border-black my-2"></div>
                        
                        <div class="flex justify-between text-[11px] font-black uppercase">
                            <span>TOTAL KESELURUHAN:</span>
                            <span>{{ formatCurrency(transaction.total_amount) }}</span>
                        </div>
                        
                        <div class="border-t border-dashed border-black my-2"></div>
                        
                        <div class="flex justify-between">
                            <span>Metode Pembayaran:</span>
                            <span class="font-bold uppercase">{{ paymentLabel(transaction.payment_method) }}</span>
                        </div>
                        
                        <!-- Cash payment details (if parsed from URL parameters) -->
                        <template v-if="transaction.payment_method === 'cash'">
                            <div class="flex justify-between" v-if="cashReceived !== null">
                                <span>Tunai Diterima:</span>
                                <span>{{ formatCurrency(cashReceived) }}</span>
                            </div>
                            <div class="flex justify-between font-bold" v-if="changeDue !== null">
                                <span>Kembalian:</span>
                                <span>{{ formatCurrency(changeDue) }}</span>
                            </div>
                        </template>
                    </div>

                    <!-- Receipt Footer -->
                    <div class="text-center space-y-1.5 text-[10px] pt-4 border-t border-dashed border-black mt-4 text-black">
                        <p class="font-extrabold text-[11px] uppercase tracking-wider">TERIMA KASIH</p>
                        <p>Atas Kunjungan & Pembelian Anda</p>
                        <p class="italic text-[9.5px]">"Fresh Coffee, Warm Vibes."</p>
                        <div class="border-t border-dotted border-black my-2 w-1/2 mx-auto"></div>
                        <p class="text-[9px]">Sistem POS: {{ appName }}</p>
                        <p class="text-[8.5px]">Waktu Cetak: {{ printDateTime }}</p>
                    </div>
                </div>

            </main>
        </div>
    </div>
</template>

<style>
/* Page setup for printing */
@media print {
    @page {
        size: auto;
        margin: 0;
    }
    
    body {
        background-color: white !important;
        color: #000000 !important;
        margin: 0 !important;
        padding: 0 !important;
        font-family: 'Courier New', Courier, monospace !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    
    /* Force high contrast pure black text/lines on thermal printer */
    * {
        color: #000000 !important;
        border-color: #000000 !important;
        fill: #000000 !important;
        stroke: #000000 !important;
        text-shadow: none !important;
        box-shadow: none !important;
    }

    /* Force bold text on all printable items for thickness/clarity at 65% scale */
    span, p, div, th, td, td *, span * {
        font-weight: bold !important;
    }
    
    .print\:hidden {
        display: none !important;
    }
    
    /* Ensure thermal formatting fits well without scaling down (optimized for 58mm paper) */
    main {
        width: 58mm !important;
        max-width: 58mm !important;
        border: none !important;
        box-shadow: none !important;
        padding: 0 !important;
        margin: 0 !important;
        width: 58mm !important;
    }

    /* Scale font size styles up to offset 80% browser scale down on 58mm paper */
    .text-\[15px\] {
        font-size: 17px !important;
    }
    .text-\[13px\] {
        font-size: 15px !important;
    }
    .text-\[12px\], .text-sm {
        font-size: 13.5px !important;
    }
    .text-\[11px\], .text-xs {
        font-size: 12.5px !important;
    }
    .text-\[10px\] {
        font-size: 11.5px !important;
    }
    .text-\[9\.5px\], .text-\[9px\], .text-\[8\.5px\] {
        font-size: 10px !important;
    }
}
</style>
