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

interface LowStockAlert {
    type: string;
    name: string;
    outlet_name: string;
    stock_qty: number;
    threshold_qty: number;
    unit: string;
}

interface TopProduct {
    name: string;
    category: string;
    qty: number;
    sales: number;
}

interface PaymentSplitItem {
    method: string;
    count: number;
    total: number;
}

interface OutletRevenueItem {
    outlet: string;
    total: number;
    count: number;
}

interface Outlet {
    id: number;
    name: string;
}

const props = defineProps<{
    kpi: {
        revenue_today: number;
        revenue_today_pct: number;
        revenue_week: number;
        revenue_month: number;
        tx_today: number;
        tx_today_pct: number;
        tx_month: number;
        avg_ticket_today: number;
        avg_ticket_pct: number;
        low_stock_count: number;
        active_outlets: number;
        active_products: number;
        total_suppliers: number;
    };
    salesTrend: { date: string; total: number; count: number }[];
    topProducts: TopProduct[];
    paymentSplit: PaymentSplitItem[];
    revenueByOutlet: OutletRevenueItem[];
    lowStockAlerts: LowStockAlert[];
    outlets: Outlet[];
    filters: { month: string; outlet_id: number | null };
    appName: string;
}>();

const activeOutletName = computed(() => {
    if (!props.filters.outlet_id) return 'Semua Outlet';
    const found = props.outlets.find(o => o.id === Number(props.filters.outlet_id));
    return found ? found.name : 'Semua Outlet';
});

const formatMonth = (monthStr: string) => {
    if (!monthStr) return '-';
    try {
        const [year, month] = monthStr.split('-');
        const date = new Date(Number(year), Number(month) - 1, 1);
        return date.toLocaleDateString('id-ID', { month: 'long', year: 'numeric' });
    } catch {
        return monthStr;
    }
};

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 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 Ringkasan - ' + appName" />

    <div 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-650/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">
                        Pratinjau Ringkasan POS
                        <span class="text-[9px] px-1.5 py-0.5 rounded bg-red-600 text-white font-bold uppercase tracking-wider">Thermal 80mm</span>
                    </h1>
                    <p class="text-[10px] text-slate-400 mt-0.5">Format struk kasir, tekan cetak untuk mencetak ke printer.</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-[80mm] min-h-[120mm] bg-white text-black p-5 shadow-2xl relative border-t-8 border-red-600 print:shadow-none print:border-t-0 print:p-0 print:w-[80mm] print:m-0">
                <!-- Tear effect top (Screen only) -->
                <div class="absolute -top-3 left-0 right-0 h-3 flex overflow-hidden select-none print:hidden">
                    <div v-for="i in 20" :key="i" class="w-4 h-4 bg-white rotate-45 transform origin-top-left -translate-y-2"></div>
                </div>

                <!-- Receipt Body Content -->
                <div class="space-y-4 font-mono text-black">
                    <!-- Brand Header -->
                    <div class="text-center space-y-1">
                        <div class="font-extrabold text-[15px] tracking-widest uppercase text-black">
                            {{ appName }}
                        </div>
                        <div class="text-[11px] font-bold text-black uppercase tracking-wide">Laporan Ringkasan Bisnis</div>
                    </div>

                    <!-- Meta Info Block -->
                    <div class="border-t border-b border-dashed border-black py-2.5 space-y-1 text-[11px] text-black">
                        <div class="flex justify-between">
                            <span>Waktu Cetak:</span>
                            <span class="font-bold text-right">{{ printDateTime }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Bulan Lap:</span>
                            <span class="font-bold uppercase text-right">{{ formatMonth(filters.month) }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Outlet:</span>
                            <span class="font-bold text-right">{{ activeOutletName }}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>Status Data:</span>
                            <span class="font-bold text-right">AKTUAL</span>
                        </div>
                    </div>

                    <!-- Section: KPI Overview -->
                    <div class="space-y-2 text-black">
                        <div class="text-[12px] font-extrabold uppercase text-center tracking-wider border border-black p-1 bg-slate-150 print:bg-white">
                            RINGKASAN UTAMA
                        </div>
                        <div class="space-y-1.5 text-[11px]">
                            <div class="flex justify-between">
                                <span>Pendapatan Hari Ini:</span>
                                <span class="font-bold">{{ formatCurrency(kpi.revenue_today) }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Transaksi Hari Ini:</span>
                                <span class="font-bold">{{ kpi.tx_today }} Txn</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Rata-rata Tiket Hari Ini:</span>
                                <span class="font-bold">{{ formatCurrency(kpi.avg_ticket_today) }}</span>
                            </div>
                            <div class="border-t border-dashed border-black my-2"></div>
                            <div class="flex justify-between font-bold">
                                <span>Omzet Bulan Ini:</span>
                                <span class="font-extrabold">{{ formatCurrency(kpi.revenue_month) }}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Transaksi Bulan Ini:</span>
                                <span class="font-bold">{{ kpi.tx_month }} Txn</span>
                            </div>
                        </div>
                    </div>

                    <div class="border-t border-dashed border-black my-2"></div>

                    <!-- Section: Top 5 Products -->
                    <div class="space-y-2 text-black">
                        <div class="text-[12px] font-extrabold uppercase text-center tracking-wider border border-black p-1 bg-slate-150 print:bg-white">
                            MENU TERLARIS (TOP 5)
                        </div>
                        <div v-if="topProducts.length === 0" class="text-center text-[11px] italic py-2">
                            Tidak ada data penjualan
                        </div>
                        <div v-else class="space-y-2.5 text-[11px]">
                            <div v-for="(item, idx) in topProducts" :key="idx" class="space-y-0.5">
                                <div class="font-bold flex justify-between">
                                    <span>#{{ idx + 1 }} {{ item.name }}</span>
                                    <span class="font-bold">{{ formatCurrency(item.sales) }}</span>
                                </div>
                                <div class="flex justify-between text-[10px] pl-3">
                                    <span>Kategori: {{ item.category }}</span>
                                    <span class="font-bold">{{ item.qty }} Porsi</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="border-t border-dashed border-black my-2"></div>

                    <!-- Section: Payment Split -->
                    <div class="space-y-2 text-black">
                        <div class="text-[12px] font-extrabold uppercase text-center tracking-wider border border-black p-1 bg-slate-150 print:bg-white">
                            METODE PEMBAYARAN
                        </div>
                        <div v-if="paymentSplit.length === 0" class="text-center text-[11px] italic py-2">
                            Tidak ada transaksi
                        </div>
                        <div v-else class="space-y-1.5 text-[11px]">
                            <div v-for="p in paymentSplit" :key="p.method" class="flex justify-between">
                                <span>{{ paymentLabel(p.method) }} ({{ p.count }} Txn)</span>
                                <span class="font-bold">{{ formatCurrency(p.total) }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Section: Outlet Contribution (if Semua Outlet) -->
                    <template v-if="!filters.outlet_id">
                        <div class="border-t border-dashed border-black my-2"></div>
                        <div class="space-y-2 text-black">
                            <div class="text-[12px] font-extrabold uppercase text-center tracking-wider border border-black p-1 bg-slate-150 print:bg-white">
                                KONTRIBUSI OUTLET
                            </div>
                            <div v-if="revenueByOutlet.length === 0" class="text-center text-[11px] italic py-2">
                                Tidak ada data outlet
                            </div>
                            <div v-else class="space-y-1.5 text-[11px]">
                                <div v-for="r in revenueByOutlet" :key="r.outlet" class="flex justify-between">
                                    <span>{{ r.outlet }} ({{ r.count }} Txn)</span>
                                    <span class="font-bold">{{ formatCurrency(r.total) }}</span>
                                </div>
                            </div>
                        </div>
                    </template>

                    <div class="border-t border-dashed border-black my-2"></div>

                    <!-- Section: Low Stock Warning -->
                    <div class="space-y-2 text-black">
                        <div class="text-[12px] font-extrabold uppercase text-center tracking-wider border border-black p-1 bg-slate-150 print:bg-white">
                            PERINGATAN STOK RENDAH
                        </div>
                        <div v-if="lowStockAlerts.length === 0" class="text-center text-[11px] font-bold py-2 uppercase tracking-wide">
                            [ SEMUA STOK AMAN ]
                        </div>
                        <div v-else class="space-y-2.5 text-[11px]">
                            <div v-for="(item, idx) in lowStockAlerts.slice(0, 10)" :key="idx" class="space-y-0.5">
                                <div class="font-bold flex justify-between">
                                    <span class="truncate pr-2">• {{ item.name }}</span>
                                    <span class="flex-shrink-0 font-bold">{{ item.stock_qty }} / {{ item.threshold_qty }} {{ item.unit }}</span>
                                </div>
                                <div class="text-[10px] pl-3 opacity-90">
                                    Outlet: {{ item.outlet_name }}
                                </div>
                            </div>
                            <div v-if="lowStockAlerts.length > 10" class="text-[10px] text-center italic mt-1 font-semibold">
                                dan {{ lowStockAlerts.length - 10 }} item lainnya...
                            </div>
                        </div>
                    </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">SISTEM POS ENTERPRISE</p>
                        <p>Dicetak otomatis via Dashboard Admin.</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-[8.5px]">Waktu Cetak: {{ printDateTime }}</p>
                    </div>
                </div>

                <!-- Tear effect bottom (Screen only) -->
                <div class="absolute -bottom-3 left-0 right-0 h-3 flex overflow-hidden select-none print:hidden rotate-180">
                    <div v-for="i in 20" :key="i" class="w-4 h-4 bg-white rotate-45 transform origin-top-left -translate-y-2"></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 */
    main {
        width: 80mm !important;
        max-width: 80mm !important;
        border: none !important;
        box-shadow: none !important;
        padding: 0 !important;
        margin: 0 !important;
    }

    /* Scale up font size styles to offset 65% browser scale down */
    .text-\[15px\] {
        font-size: 22px !important;
    }
    .text-\[12px\] {
        font-size: 18px !important;
    }
    .text-\[11px\] {
        font-size: 16.5px !important;
    }
    .text-\[10px\] {
        font-size: 15px !important;
    }
    .text-\[9\.5px\] {
        font-size: 13.5px !important;
    }
    .text-\[8\.5px\] {
        font-size: 12.5px !important;
    }
}
</style>
