<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]"
            >
                <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>

                <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">
                            <KasirTransaksiList
                                :transaksi="transaksi.data || []"
                                :loading="loading"
                                :pagination="transaksi.pagination || null"
                                @page-change="handlePageChange"
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <ModalConfirm
            v-if="showConfirm"
            title="Konfirmasi"
            :message="confirmMessage"
            @confirm="handleConfirm"
            @cancel="showConfirm = false"
        />
    </mainLayout>
</template>

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

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

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

const showConfirm = ref(false);
const confirmMessage = ref("Apakah kamu yakin?");
let lastTransaksi = null;

const handleConfirm = () => {
    showConfirm.value = false;
    console.log("User konfirmasi, cetak struk di sini...", lastTransaksi);
};

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

        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
        };

    } catch (err) {
        console.error("Gagal fetch transaksi hari ini:", err);
        transaksi.value = { data: [], pagination: null };
        alert("Gagal memuat transaksi hari ini");
    } finally {
        loading.value = false;
    }
};

const handlePageChange = (page) => {
    if (page >= 1 && page <= (transaksi.value.pagination?.last_page || 1)) {
        fetchTransaksiHariIni(page);
    }
};

const handleTransaksiSaved = async (newTransaksi) => {
    // Format data transaksi baru
    const formattedNewTransaksi = {
        id: newTransaksi.id,
        kode_transaksi: newTransaksi.kode_transaksi,
        created_at: newTransaksi.created_at,
        total_harga: newTransaksi.total_harga || 0,
        itemTransaksi: newTransaksi.itemTransaksi || newTransaksi.items || [],
        pendapatan: newTransaksi.total_harga || 0,
        total_items: (newTransaksi.itemTransaksi || newTransaksi.items || []).length,
        tanggal: new Date(newTransaksi.created_at).toLocaleDateString('id-ID'),
        nama_pembeli: newTransaksi.nama_pembeli,
        alamat: newTransaksi.alamat,
        no_hp: newTransaksi.no_hp,
        ongkos_bikin: newTransaksi.ongkos_bikin,
        nama_sales: newTransaksi.nama_sales
    };

    // Tambahkan ke awal list
    transaksi.value.data.unshift(formattedNewTransaksi);
    lastTransaksi = formattedNewTransaksi;

    // Update pagination
    if (transaksi.value.pagination) {
        transaksi.value.pagination.total += 1;
        // Hapus item terakhir jika melebihi limit
        if (transaksi.value.data.length > limit) {
            transaksi.value.data.pop();
        }
    }

    // Tidak perlu modal konfirmasi lagi karena sudah ada StrukView
    // confirmMessage.value = "Transaksi berhasil disimpan. Cetak struk sekarang?";
    // showConfirm.value = true;
};

let refreshInterval = null;
const startAutoRefresh = () => {
    if (refreshInterval) clearInterval(refreshInterval);
    refreshInterval = setInterval(() => {
        fetchTransaksiHariIni(currentPage.value);
    }, 30000); // Refresh setiap 30 detik (sebelumnya 10 detik)
};

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

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

onUnmounted(() => {
    stopAutoRefresh();
});
</script>
