<script setup lang="ts">
import { computed } from 'vue';
import { Head } from '@inertiajs/vue3';
import { Printer, X, FileText, Calendar, Building, DollarSign, ShoppingBag, TrendingUp, AlertTriangle } from 'lucide-vue-next';
import { useAuth } from '@/Composables/useAuth';

const { settings } = useAuth();

interface LowStockAlert {
    type: 'Ingredient' | 'Retail Product';
    name: string;
    outlet_name: string;
    stock_qty: number;
    threshold_qty: number;
    unit: string;
}

interface SalesTrendPoint {
    date: string;
    total: number;
    count: number;
}

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

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

interface WaiterData {
    name: string;
    transactions: number;
    sales: number;
}

interface TableTurnoverData {
    number: string;
    transactions: number;
    sales: number;
}

interface PeakHourData {
    hour: string;
    transactions: number;
    sales: number;
}

const props = defineProps<{
    metrics: {
        total_revenue: number;
        total_transactions: number;
        average_ticket: number;
        low_stock_count: number;
        total_cogs: number;
        food_cost_percentage: number;
        total_waste_cost: number;
    };
    lowStockAlerts: LowStockAlert[];
    salesTrend: SalesTrendPoint[];
    topProducts: TopProduct[];
    outlets: Outlet[];
    filters: {
        outlet_id: number | null;
        start_date: string;
        end_date: string;
    };
    waiterPerformance: WaiterData[];
    tableTurnover: TableTurnoverData[];
    peakHours: PeakHourData[];
}>();

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 formatDate = (dateStr: string) => {
    if (!dateStr) return '-';
    const d = new Date(dateStr);
    return d.toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
};

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

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

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

<template>
    <Head :title="'Cetak Laporan - ' + (settings().site_name || 'CafePOS')" />

    <div class="min-h-screen bg-slate-100 dark:bg-slate-900 print:bg-white text-slate-800 print:text-black font-sans antialiased">
        <!-- Sticky Action Header (Hidden on Print) -->
        <div class="sticky top-0 bg-white dark:bg-slate-950 border-b border-slate-200 dark:border-slate-800 px-6 py-4 flex items-center justify-between shadow-sm z-50 print:hidden select-none">
            <div class="flex items-center gap-2">
                <FileText class="h-5 w-5 text-red-600" />
                <div>
                    <h1 class="text-sm font-bold text-slate-900 dark:text-slate-100">Pratinjau Cetak Laporan</h1>
                    <p class="text-[10px] text-slate-500">Sesuaikan tata letak cetak di jendela browser Anda.</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-lg text-xs font-bold transition-colors cursor-pointer flex items-center gap-2 shadow-sm"
                >
                    <Printer class="h-4 w-4" />
                    <span>Cetak Laporan</span>
                </button>
                <button
                    @click="closeWindow"
                    class="px-4 py-2 border border-slate-200 dark:border-slate-850 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-xs font-bold transition-colors cursor-pointer flex items-center gap-2 text-slate-700 dark:text-slate-300 bg-white dark:bg-transparent"
                >
                    <X class="h-4 w-4" />
                    <span>Tutup</span>
                </button>
            </div>
        </div>

        <!-- Print Container Sheet -->
        <main class="max-w-4xl mx-auto my-6 p-8 md:p-12 bg-white border border-slate-200 dark:border-slate-800 print:border-0 rounded-xl shadow-md print:shadow-none print:my-0 print:p-0">
            
            <!-- Document Header -->
            <div class="flex flex-col sm:flex-row justify-between items-start gap-4 pb-6 border-b-2 border-slate-900 print:border-slate-800">
                <div class="space-y-1">
                    <span class="text-xs font-bold uppercase tracking-widest text-red-600">{{ settings().site_name }}</span>
                    <h2 class="text-2xl font-black text-slate-900 tracking-tight">LAPORAN AKTIVITAS KEUANGAN</h2>
                    <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-500 font-medium">
                        <span class="flex items-center gap-1">
                            <Building class="h-3.5 w-3.5" />
                            Outlet: <strong class="text-slate-800">{{ activeOutletName }}</strong>
                        </span>
                        <span class="flex items-center gap-1">
                            <Calendar class="h-3.5 w-3.5" />
                            Periode: <strong class="text-slate-800">{{ formatDate(filters.start_date) }} - {{ formatDate(filters.end_date) }}</strong>
                        </span>
                    </div>
                </div>
                <div class="text-right sm:text-right text-xs text-slate-500 space-y-1">
                    <p>Dicetak pada: <strong class="text-slate-800">{{ printDate }}</strong></p>
                    <p>Status Laporan: <span class="px-1.5 py-0.5 bg-emerald-50 text-emerald-800 font-bold rounded text-[9px] uppercase border border-emerald-200">Finalized</span></p>
                </div>
            </div>

            <!-- Executive Summary Cards Grid -->
            <div class="grid grid-cols-3 md:grid-cols-6 gap-4 py-8">
                <!-- Omzet -->
                <div class="border border-slate-200 rounded-xl p-4 flex flex-col justify-between">
                    <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Total Pendapatan</span>
                    <h4 class="text-base font-extrabold text-slate-900 mt-1">
                        Rp {{ Number(metrics.total_revenue).toLocaleString('id-ID') }}
                    </h4>
                    <span class="text-[9px] text-slate-400 mt-2 flex items-center gap-1 font-medium">
                        <DollarSign class="h-3 w-3 text-red-600" />
                        Sales Revenue
                    </span>
                </div>

                <!-- Transactions Count -->
                <div class="border border-slate-200 rounded-xl p-4 flex flex-col justify-between">
                    <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Total Transaksi</span>
                    <h4 class="text-base font-extrabold text-slate-900 mt-1">
                        {{ metrics.total_transactions }} Orders
                    </h4>
                    <span class="text-[9px] text-slate-400 mt-2 flex items-center gap-1 font-medium">
                        <ShoppingBag class="h-3 w-3 text-red-600" />
                        Completed Tickets
                    </span>
                </div>

                <!-- Average Ticket Value -->
                <div class="border border-slate-200 rounded-xl p-4 flex flex-col justify-between">
                    <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Rata-Rata Transaksi</span>
                    <h4 class="text-base font-extrabold text-slate-900 mt-1">
                        Rp {{ Number(metrics.average_ticket).toLocaleString('id-ID') }}
                    </h4>
                    <span class="text-[9px] text-slate-400 mt-2 flex items-center gap-1 font-medium">
                        <TrendingUp class="h-3 w-3 text-red-600" />
                        Average Spend
                    </span>
                </div>

                <!-- Food Cost / COGS HPP -->
                <div class="border border-slate-200 rounded-xl p-4 flex flex-col justify-between">
                    <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Total HPP</span>
                    <h4 class="text-base font-extrabold text-slate-900 mt-1">
                        Rp {{ Number(metrics.total_cogs).toLocaleString('id-ID') }}
                    </h4>
                    <span class="text-[9px] text-slate-400 mt-2 flex items-center gap-1 font-medium">
                        <DollarSign class="h-3 w-3 text-red-600" />
                        Cost of Goods
                    </span>
                </div>

                <!-- Food Cost Ratio -->
                <div class="border border-slate-200 rounded-xl p-4 flex flex-col justify-between">
                    <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Rasio Food Cost</span>
                    <h4 class="text-base font-extrabold text-slate-900 mt-1">
                        {{ Number(metrics.food_cost_percentage).toFixed(1) }}%
                    </h4>
                    <span class="text-[9px] text-slate-400 mt-2 flex items-center gap-1 font-medium">
                        <TrendingUp class="h-3 w-3 text-red-600" />
                        Cost Ratio
                    </span>
                </div>

                <!-- Low Stock Alert Warning -->
                <div class="border rounded-xl p-4 flex flex-col justify-between" :class="metrics.low_stock_count > 0 ? 'border-amber-300 bg-amber-50/20' : 'border-slate-200'">
                    <span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Peringatan Inventori</span>
                    <h4 class="text-base font-extrabold mt-1" :class="metrics.low_stock_count > 0 ? 'text-amber-700' : 'text-slate-900'">
                        {{ metrics.low_stock_count }} Items
                    </h4>
                    <span class="text-[9px] text-slate-400 mt-2 flex items-center gap-1 font-medium">
                        <AlertTriangle class="h-3 w-3 text-amber-500" />
                        Safety Level
                    </span>
                </div>
            </div>

            <!-- Detail Tables Section -->
            <div class="space-y-8">
                <!-- 1. Top Selling Menus -->
                <div class="space-y-3">
                    <h3 class="text-xs font-bold text-slate-900 uppercase tracking-widest flex items-center gap-1.5 pb-1.5 border-b border-slate-200">
                        <span class="h-1.5 w-1.5 bg-slate-800 rounded-full"></span>
                        Daftar Menu Terlaris (Top 5)
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="w-full border-collapse text-left text-xs border border-slate-200">
                            <thead>
                                <tr class="bg-slate-50 font-bold border-b border-slate-200 text-slate-600">
                                    <th class="p-2.5 w-16 text-center">Rank</th>
                                    <th class="p-2.5">Nama Menu</th>
                                    <th class="p-2.5">Kategori</th>
                                    <th class="p-2.5 text-center">Porsi Terjual</th>
                                    <th class="p-2.5 text-right pr-4">Total Omzet</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-if="topProducts.length === 0">
                                    <td colspan="5" class="p-4 text-center text-slate-400 italic">Belum ada pesanan yang tercatat.</td>
                                </tr>
                                <tr v-for="(item, idx) in topProducts" :key="idx" class="hover:bg-slate-50/50">
                                    <td class="p-2.5 text-center font-bold text-slate-500">#{{ idx + 1 }}</td>
                                    <td class="p-2.5 font-bold text-slate-900">{{ item.name }}</td>
                                    <td class="p-2.5 text-slate-500">{{ item.category }}</td>
                                    <td class="p-2.5 text-center font-semibold">{{ item.qty }} porsi</td>
                                    <td class="p-2.5 text-right font-mono pr-4 font-bold">Rp {{ Number(item.sales).toLocaleString('id-ID') }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 2. Daily Sales Revenue Trend -->
                <div class="space-y-3">
                    <h3 class="text-xs font-bold text-slate-900 uppercase tracking-widest flex items-center gap-1.5 pb-1.5 border-b border-slate-200">
                        <span class="h-1.5 w-1.5 bg-slate-800 rounded-full"></span>
                        Tren Pendapatan Harian
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="w-full border-collapse text-left text-xs border border-slate-200">
                            <thead>
                                <tr class="bg-slate-50 font-bold border-b border-slate-200 text-slate-600">
                                    <th class="p-2.5">Tanggal</th>
                                    <th class="p-2.5 text-center">Jumlah Transaksi</th>
                                    <th class="p-2.5 text-right pr-4">Omzet Harian</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-if="salesTrend.length === 0">
                                    <td colspan="3" class="p-4 text-center text-slate-400 italic">Tidak ada data penjualan untuk rentang waktu ini.</td>
                                </tr>
                                <tr v-for="(p, idx) in salesTrend" :key="idx" class="hover:bg-slate-50/50">
                                    <td class="p-2.5 font-medium text-slate-800">{{ formatDate(p.date) }}</td>
                                    <td class="p-2.5 text-center font-semibold">{{ p.count }} kali</td>
                                    <td class="p-2.5 text-right font-mono pr-4 font-bold text-slate-900">Rp {{ Number(p.total).toLocaleString('id-ID') }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 3. Waiter & Table Performance -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 avoid-page-break">
                    <!-- Waiter Performance -->
                    <div class="space-y-3">
                        <h3 class="text-xs font-bold text-slate-900 uppercase tracking-widest flex items-center gap-1.5 pb-1.5 border-b border-slate-200">
                            <span class="h-1.5 w-1.5 bg-slate-800 rounded-full"></span>
                            Performa Pelayan
                        </h3>
                        <table class="w-full border-collapse text-left text-xs border border-slate-200">
                            <thead>
                                <tr class="bg-slate-50 font-bold border-b border-slate-200 text-slate-600">
                                    <th class="p-2.5">Nama Pelayan</th>
                                    <th class="p-2.5 text-center">Transaksi</th>
                                    <th class="p-2.5 text-right pr-4">Total Penjualan</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-if="waiterPerformance.length === 0">
                                    <td colspan="3" class="p-4 text-center text-slate-400 italic">Belum ada data.</td>
                                </tr>
                                <tr v-for="w in waiterPerformance" :key="w.name" class="hover:bg-slate-50/50">
                                    <td class="p-2.5 font-bold text-slate-900">{{ w.name }}</td>
                                    <td class="p-2.5 text-center font-semibold">{{ w.transactions }}</td>
                                    <td class="p-2.5 text-right font-mono pr-4 font-bold">Rp {{ Number(w.sales).toLocaleString('id-ID') }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Table Turnover -->
                    <div class="space-y-3">
                        <h3 class="text-xs font-bold text-slate-900 uppercase tracking-widest flex items-center gap-1.5 pb-1.5 border-b border-slate-200">
                            <span class="h-1.5 w-1.5 bg-slate-800 rounded-full"></span>
                            Okupansi Meja
                        </h3>
                        <table class="w-full border-collapse text-left text-xs border border-slate-200">
                            <thead>
                                <tr class="bg-slate-50 font-bold border-b border-slate-200 text-slate-600">
                                    <th class="p-2.5">No. Meja</th>
                                    <th class="p-2.5 text-center">Frekuensi</th>
                                    <th class="p-2.5 text-right pr-4">Total Transaksi</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-if="tableTurnover.length === 0">
                                    <td colspan="3" class="p-4 text-center text-slate-400 italic">Belum ada data.</td>
                                </tr>
                                <tr v-for="t in tableTurnover" :key="t.number" class="hover:bg-slate-50/50">
                                    <td class="p-2.5 font-bold text-slate-900">Meja {{ t.number }}</td>
                                    <td class="p-2.5 text-center font-semibold">{{ t.transactions }}x</td>
                                    <td class="p-2.5 text-right font-mono pr-4 font-bold">Rp {{ Number(t.sales).toLocaleString('id-ID') }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 4. Peak Hours Operational -->
                <div class="space-y-3 avoid-page-break">
                    <h3 class="text-xs font-bold text-slate-900 uppercase tracking-widest flex items-center gap-1.5 pb-1.5 border-b border-slate-200">
                        <span class="h-1.5 w-1.5 bg-slate-800 rounded-full"></span>
                        Jam Sibuk Operasional (Peak Hours)
                    </h3>
                    <table class="w-full border-collapse text-left text-xs border border-slate-200">
                        <thead>
                            <tr class="bg-slate-50 font-bold border-b border-slate-200 text-slate-600">
                                <th class="p-2.5">Jam Operasional</th>
                                <th class="p-2.5 text-center">Frekuensi Transaksi</th>
                                <th class="p-2.5 text-right pr-4">Total Penjualan</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <tr v-if="peakHours.length === 0">
                                <td colspan="3" class="p-4 text-center text-slate-400 italic">Belum ada data.</td>
                            </tr>
                            <tr v-for="h in peakHours" :key="h.hour" class="hover:bg-slate-50/50">
                                <td class="p-2.5 font-medium text-slate-800">{{ h.hour }}</td>
                                <td class="p-2.5 text-center font-semibold">{{ h.transactions }} Transaksi</td>
                                <td class="p-2.5 text-right font-mono pr-4 font-bold">Rp {{ Number(h.sales).toLocaleString('id-ID') }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 5. Safety Stock Alerts -->
                <div class="space-y-3">
                    <h3 class="text-xs font-bold text-slate-900 uppercase tracking-widest flex items-center gap-1.5 pb-1.5 border-b border-slate-200">
                        <span class="h-1.5 w-1.5 bg-slate-800 rounded-full"></span>
                        Peringatan Stok Bahan & Produk Menipis
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="w-full border-collapse text-left text-xs border border-slate-200">
                            <thead>
                                <tr class="bg-slate-50 font-bold border-b border-slate-200 text-slate-600">
                                    <th class="p-2.5">Nama Item</th>
                                    <th class="p-2.5">Tipe Stok</th>
                                    <th class="p-2.5">Lokasi Outlet</th>
                                    <th class="p-2.5 text-center">Stok Saat Ini</th>
                                    <th class="p-2.5 text-right pr-4">Batas Aman Minimum</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <tr v-if="lowStockAlerts.length === 0">
                                    <td colspan="5" class="p-4 text-center text-slate-400 italic">Semua persediaan bahan baku dan retail product di outlet aman.</td>
                                </tr>
                                <tr v-for="(warn, idx) in lowStockAlerts" :key="idx" class="hover:bg-slate-50/50 text-slate-700">
                                    <td class="p-2.5 font-bold text-slate-900">{{ warn.name }}</td>
                                    <td class="p-2.5">
                                        <span class="px-1.5 py-0.5 rounded bg-slate-100 text-[10px] font-semibold border border-slate-200">
                                            {{ warn.type }}
                                        </span>
                                    </td>
                                    <td class="p-2.5">{{ warn.outlet_name }}</td>
                                    <td class="p-2.5 text-center text-red-600 font-bold">
                                        {{ Number(warn.stock_qty).toLocaleString('id-ID') }} {{ warn.unit }}
                                    </td>
                                    <td class="p-2.5 text-right pr-4 font-mono">
                                        {{ Number(warn.threshold_qty).toLocaleString('id-ID') }} {{ warn.unit }}
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Signature block (Prepared & Approved by) -->
            <div class="mt-16 pt-8 border-t border-slate-200 flex justify-between gap-12 text-xs avoid-page-break" style="page-break-inside: avoid; break-inside: avoid;">
                <div class="flex flex-col space-y-16 w-48 text-center">
                    <div>
                        <p class="text-slate-450 uppercase tracking-widest text-[9px] font-bold">Prepared By</p>
                        <p class="font-semibold text-slate-800 mt-1">Manajer Keuangan</p>
                    </div>
                    <div class="border-b border-slate-400 w-full"></div>
                    <p class="text-slate-450 font-medium">Tanggal: _______________</p>
                </div>
                <div class="flex flex-col space-y-16 w-48 text-center">
                    <div>
                        <p class="text-slate-455 uppercase tracking-widest text-[9px] font-bold">Approved By</p>
                        <p class="font-semibold text-slate-800 mt-1">Pemilik (Owner)</p>
                    </div>
                    <div class="border-b border-slate-400 w-full"></div>
                    <p class="text-slate-455 font-medium">Tanggal: _______________</p>
                </div>
            </div>

            <!-- Footer print page margins info -->
            <div class="hidden print:flex justify-between items-center mt-12 pt-4 border-t border-slate-100 text-[9px] text-slate-400 font-medium">
                <span>Dokumen rahasia - Khusus penggunaan internal CafePOS.</span>
                <span>Halaman 1 dari 1</span>
            </div>
        </main>
    </div>
</template>

<style>
@media print {
    body {
        background-color: white !important;
        color: #000000 !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        font-family: system-ui, -apple-system, sans-serif !important;
    }
    
    /* Force high contrast black text and borders in print */
    h2, h3, h4, th, td, p, span, strong, div {
        color: #000000 !important;
    }

    table {
        border-color: #000000 !important;
    }

    th, td {
        border-color: #000000 !important;
    }

    .divide-y > * + * {
        border-color: #000000 !important;
    }
    
    .border {
        border-color: #000000 !important;
    }

    .border-b-2 {
        border-bottom-width: 2px !important;
        border-color: #000000 !important;
    }

    .border-t {
        border-color: #000000 !important;
    }

    .border-b {
        border-color: #000000 !important;
    }
    
    @page {
        size: A4;
        margin: 1.5cm;
    }
    
    .avoid-page-break {
        page-break-inside: avoid !important;
        break-inside: avoid !important;
    }
}
</style>
