<template>
    <mainLayout>
        <div class="lg:p-2 pt-6">
            <div
                class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3 sm:gap-2 mx-auto min-h-[75vh]"
            >
                <!-- Left Section - Form Kasir -->
                <div class="lg:col-span-3">
                    <div
                        class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden h-auto lg:h-full"
                    >
                        <div class="p-2 sm:p-3 md:p-4 h-auto lg:h-full">
                            <KasirForm @transaksi-saved="handleTransaksiSaved" />
                        </div>
                    </div>
                </div>

                <!-- Right Section - Transaction List -->
                <div class="lg:col-span-2">
                    <div
                        class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden lg:h-fit sticky top-4 max-h-[70vh] overflow-y-auto"
                    >
                        <div class="p-3 sm:p-4 md:p-6">
                            <!-- Simplified Transaction List - Hari Ini Only -->
                            <KasirTransaksiList
                                :transaksi="transaksi.data || []"
                                :loading="loading"
                                :pagination="transaksi.pagination || null"
                                @page-change="handlePageChange"
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </mainLayout>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";

import mainLayout from "../layouts/mainLayout.vue";
import KasirForm from "../components/KasirForm.vue";
import KasirTransaksiList from "../components/KasirTransaksiList.vue";

const transaksi = ref({
  data: [],
  pagination: null
});
const loading = ref(true);
const currentPage = ref(1);
const limit = 10;

// Fetch hanya transaksi hari ini
const fetchTransaksiHariIni = async (page = 1) => {
    try {
        loading.value = true;
        currentPage.value = page;
        
        // Hanya fetch transaksi hari ini
        const today = new Date().toISOString().split('T')[0];
        const params = new URLSearchParams({
            limit: limit,
            page: page,
            start_date: today,
            end_date: today
        }).toString();

        console.log('Fetching transaksi hari ini:', params);

        const res = await axios.get(`/api/transaksi?${params}`, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
        });

        transaksi.value = {
            data: res.data.data || [],
            pagination: res.data.pagination || null
        };
        
        console.log("Transaksi hari ini:", transaksi.value);

    } catch (err) {
        console.error("Gagal fetch transaksi hari ini:", err);
        transaksi.value = { data: [], pagination: null };
        
        let errorMessage = 'Gagal memuat transaksi hari ini';
        if (err.response) {
            errorMessage += `: ${err.response.status} - ${err.response.data?.message || err.response.statusText}`;
        } else if (err.request) {
            errorMessage += ': Tidak ada respon dari server';
        } else {
            errorMessage += `: ${err.message}`;
        }
        
        alert(errorMessage);
    } finally {
        loading.value = false;
    }
};

// Handle pagination
const handlePageChange = (page) => {
    console.log('Page changed to:', page);
    
    if (page >= 1 && page <= (transaksi.value.pagination?.last_page || 1)) {
        fetchTransaksiHariIni(page);
    }
};

// Handle transaksi baru dari KasirForm
const handleTransaksiSaved = async (newTransaksi) => {
    console.log("Transaksi baru disimpan:", newTransaksi);
    
    // Karena ini transaksi hari ini, selalu tambahkan ke list
    const formattedNewTransaksi = {
        id: newTransaksi.id,
        kode_transaksi: newTransaksi.kode_transaksi,
        created_at: newTransaksi.created_at,
        total_harga: newTransaksi.total_harga || 0,
        itemTransaksi: newTransaksi.itemTransaksi || [],
        pendapatan: newTransaksi.total_harga || 0,
        total_items: newTransaksi.itemTransaksi?.length || 0,
        tanggal: new Date(newTransaksi.created_at).toLocaleDateString('id-ID')
    };
    
    // Tambahkan ke awal array
    transaksi.value.data.unshift(formattedNewTransaksi);
    
    // Update pagination
    if (transaksi.value.pagination) {
        transaksi.value.pagination.total += 1;
        
        // Jika sudah penuh, hapus item terakhir
        if (transaksi.value.data.length > limit) {
            transaksi.value.data.pop();
        }
    }
    
    console.log("Transaksi baru ditambahkan ke list hari ini");
};

// Auto-refresh setiap 10 detik untuk update real-time
let refreshInterval = null;

const startAutoRefresh = () => {
    if (refreshInterval) clearInterval(refreshInterval);
    refreshInterval = setInterval(() => {
        fetchTransaksiHariIni(currentPage.value);
    }, 10000); // 10 detik
};

const stopAutoRefresh = () => {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
};

// Initialize
onMounted(async () => {
    await fetchTransaksiHariIni();
    startAutoRefresh();
});

// Cleanup
import { onUnmounted } from 'vue';
onUnmounted(() => {
    stopAutoRefresh();
});
</script>
