<template>
  <div class="overflow-x-auto">
    <h3 class="text-lg font-semibold mb-4 text-gray-800">Transaksi</h3>
    <table class="w-full min-w-[500px] border border-B rounded-lg text-sm">
      <thead class="bg-A text-D">
        <tr>
          <th class="border border-B p-2 text-left">Tanggal</th>
          <th class="border border-B p-2 text-left">Kode Transaksi</th>
          <th class="border border-B p-2 text-left">Pendapatan</th>
          <th class="border border-B p-2 text-center">Detail Item</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="trx in props.transaksi" :key="trx.id" class="hover:bg-A">
          <td class="border border-B p-2">{{ trx.tanggal }}</td>
          <td class="border border-B p-2">{{ trx.kode_transaksi }}</td>
          <td class="border border-B p-2">Rp{{ (trx.total_harga || 0).toLocaleString() }}</td>
          <td class="border border-B p-2 text-center">
            <button
              @click="lihatDetail(trx)"
              class="px-3 py-1 rounded-md bg-D text-A hover:bg-D/80 transition">
              Detail
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- Modal Detail Transaksi -->
    <StrukView
      :isOpen="isDetailOpen"
      :transaksi="selectedTransaksi"
      @close="closeDetail"
    />

    <!-- Loading Modal -->
    <div v-if="isLoading"
      class="fixed inset-0 bg-black/75 flex items-center justify-center z-[10000]">
      <div class="bg-white p-6 rounded-lg flex items-center gap-3">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
        <span>Memuat detail transaksi...</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import StrukView from './StrukView.vue'

const props = defineProps({
  transaksi: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['detail'])

// State untuk modal detail
const isDetailOpen = ref(false)
const selectedTransaksi = ref({})
const isLoading = ref(false)

// Fungsi untuk melihat detail transaksi
const lihatDetail = async (trx) => {
  try {
    isLoading.value = true
    console.log('Fetching detail untuk transaksi:', trx)

    // Fetch detail transaksi dengan semua relasi
    const response = await axios.get(`/api/transaksi/${trx.id}`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    })

    console.log('Response detail transaksi:', response.data)
    selectedTransaksi.value = response.data
    isDetailOpen.value = true

  } catch (error) {
    console.error('Error fetching transaksi detail:', error)

    let errorMessage = 'Gagal memuat detail transaksi'
    if (error.response) {
      errorMessage += `: ${error.response.status} - ${error.response.data?.message || error.response.statusText}`
    } else if (error.request) {
      errorMessage += ': Tidak ada respon dari server'
    } else {
      errorMessage += `: ${error.message}`
    }

    alert(errorMessage)
  } finally {
    isLoading.value = false
  }
}

// Fungsi untuk menutup modal detail
const closeDetail = () => {
  isDetailOpen.value = false
  selectedTransaksi.value = {}
}
</script>
