<template>
  <div>
    <!-- Loading -->
    <div v-if="loading" class="text-center py-6">Loading...</div>

    <!-- Error -->
    <div v-else-if="error" class="text-center text-red-500 py-6">{{ error }}</div>

    <!-- Kalau hasil search kosong -->
    <div
      v-else-if="filteredTrays.length === 0"
      class="text-center text-gray-500 py-6"
    >
      Nampan tidak ditemukan.
    </div>

    <!-- Grid nampan -->
    <div
      v-else
      class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
    >
      <div
        v-for="tray in filteredTrays"
        :key="tray.id"
        class="border rounded-lg p-4 shadow-sm hover:shadow-md transition"
      >
        <!-- Header Nampan -->
        <div class="flex justify-between items-center mb-3">
          <h2 class="font-bold text-lg" style="color: #102C57;">{{ tray.nama }}</h2>
          <div class="flex gap-2">
            <button 
  class="p-2 rounded bg-yellow-400 hover:bg-yellow-500"
  @click="emit('edit', tray)"
>
  ✏️
</button>
            <button 
  class="bg-red-500 text-white p-1 rounded"
  @click="emit('delete', tray.id)"
>
  🗑️
</button>
          </div>
        </div>

        <!-- Isi Nampan -->
        <div 
  v-if="tray.items && tray.items.length > 0" 
  class="space-y-2 max-h-64 overflow-y-auto pr-2"
>
  <div
    v-for="item in tray.items"
    :key="item.id"
    class="flex justify-between items-center border rounded-lg p-2"
  >
          
            <!-- Gambar + Info -->
            <div class="flex items-center gap-3">
              <img
                 v-if="item.produk.foto && item.produk.foto.length > 0"
      :src="item.produk.foto[0].url"
      alt="foto produk"
      class="w-12 h-12 object-cover rounded"
              />
              <div>
                <p class="text-sm" style="color: #102C57;">{{ item.produk.nama }}</p>
                <p class="text-sm" style="color: #102C57;">{{ item.produk.kategori }}</p>
                <p class="text-sm" style="color: #102C57;">{{ item.produk.harga_jual.toLocaleString() }}</p>
              </div>
            </div>
            <!-- Berat -->
            <span class="font-medium">{{ item.produk.berat }}g</span>
          </div>
        </div>

        <!-- Kalau nampan kosong -->
        <div v-else class="text-gray-400 text-center py-4">
          Nampan kosong.<br />
          Masuk ke menu <b>Brankas</b> untuk memindahkan item ke nampan.
        </div>

        <!-- Total Berat -->
        <div class="border-t mt-3 pt-2 text-right font-semibold">
          Berat Total: {{ totalWeight(tray) }}g
        </div>
      </div>
    </div>
  </div>
</template>


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

// terima search dari parent
const props = defineProps({
  search: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["edit", "delete"])

const trays = ref([]);
const loading = ref(true);
const error = ref(null);

// hitung total berat
const totalWeight = (tray) => {
  if (!tray.items) return 0;
  return tray.items.reduce((sum, item) => sum + (item.produk.berat || 0), 0);
};

// ambil data dari backend
onMounted(async () => {
  try {
    const [nampanRes, itemRes] = await Promise.all([
      axios.get("/api/nampan"),
      axios.get("/api/item")
    ]);

    const nampans = nampanRes.data;
    const items = itemRes.data;

    // mapping items ke nampan
    trays.value = nampans.map(tray => {
      return {
        ...tray,
        items: items.filter(item => item.id_nampan === tray.id)
      };
    });

    console.log("Nampan dengan items:", trays.value);
  } catch (err) {
    error.value = err.message || "Gagal mengambil data";
  } finally {
    loading.value = false;
  }
});

// filter berdasarkan nama nampan
const filteredTrays = computed(() => {
  if (!props.search) return trays.value;
  return trays.value.filter((tray) =>
    tray.nama.toLowerCase().includes(props.search.toLowerCase())
  );
});
</script>