<template>
  <div>
    <!-- Daftar Item -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      <div
        v-for="item in filteredItems"
        :key="item.id"
        class="flex justify-between items-center border rounded-lg p-3 shadow-sm hover:shadow-md transition cursor-pointer"
        @click="openMovePopup(item)"
      >
        <!-- Gambar & Info Produk -->
        <div class="flex items-center gap-3">
          <img
            v-if="item.produk.foto?.length"
            :src="item.produk.foto[0].url"
            class="size-12 object-contain"
          />
          <div>
            <p class="font-semibold">{{ item.produk.nama }}</p>
            <p class="text-sm text-gray-500">ID: {{ item.id }}</p>
          </div>
        </div>

        <!-- Berat -->
        <span class="font-medium">{{ item.produk.berat }}g</span>
      </div>
    </div>

    <!-- Modal Pindah Nampan -->
    <div
      v-if="isPopupVisible"
      class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50"
    >
      <div class="bg-white rounded-xl shadow-lg max-w-sm w-full p-6 relative">
        <!-- QR Code -->
        <div class="flex justify-center mb-4">
          <div class="p-2 border rounded-lg">
            <img :src="qrCodeUrl" alt="QR Code" class="size-36" />
          </div>
        </div>

        <!-- Info Produk -->
        <div class="text-center text-gray-700 font-medium mb-1">
          {{ selectedItem?.produk?.nama }}
        </div>
        <div class="text-center text-gray-500 text-sm mb-4">
          {{ selectedItem?.produk?.kategori }}
        </div>

        <!-- Dropdown pilih nampan -->
        <div class="mb-4">
          <label for="tray-select" class="block text-sm font-medium mb-1">
            Nama Nampan
          </label>
          <select
            id="tray-select"
            v-model="selectedTrayId"
            class="w-full rounded-md border shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
          >
            <option value="" disabled>Brankas</option>
            <option v-for="tray in trays" :key="tray.id" :value="tray.id">
              {{ tray.nama }}
            </option>
          </select>
        </div>

        <!-- Tombol -->
        <div class="flex justify-end gap-2">
          <button
            @click="closePopup"
            class="px-4 py-2 rounded border text-gray-700 hover:bg-gray-100 transition"
          >
            Batal
          </button>
          <button
            @click="saveMove"
            :disabled="!selectedTrayId"
            class="px-4 py-2 rounded text-white transition"
            :class="selectedTrayId ? 'bg-orange-500 hover:bg-orange-600' : 'bg-gray-400 cursor-not-allowed'"
          >
            Simpan
          </button>
        </div>
      </div>
    </div>
  </div>
</template>



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

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

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

// --- state modal
const isPopupVisible = ref(false);
const selectedItem = ref(null);
const selectedTrayId = ref("");

// QR Code generator
const qrCodeUrl = computed(() => {
  if (selectedItem.value) {
    const data = `ITM-${selectedItem.value.id}-${selectedItem.value.produk.nama.replace(/\s/g, "")}`;
    return `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(
      data
    )}`;
  }
  return "";
});

// --- fungsi modal
const openMovePopup = (item) => {
  selectedItem.value = item;
  if (item.id_nampan) {
    // ✅ sudah ada di nampan tertentu
    selectedTrayId.value = item.id_nampan;
  } else {
    // 🗄️ kalau belum ada, default ke "Brankas"
    const brankas = trays.value.find(t => t.nama.toLowerCase() === "brankas");
    selectedTrayId.value = brankas ? brankas.id : "";
  }
  isPopupVisible.value = true;
};
const closePopup = () => {
  isPopupVisible.value = false;
  selectedItem.value = null;
  selectedTrayId.value = "";
};

const saveMove = async () => {
  if (!selectedTrayId.value || !selectedItem.value) return;
  try {
    await axios.put(
      `/api/item/${selectedItem.value.id}`,
      {
        id_nampan: selectedTrayId.value,
        id_produk: selectedItem.value.id_produk,
      },
      {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      }
    );

    await refreshData();
    closePopup();
  } catch (err) {
    console.error("Gagal memindahkan item:", err.response?.data || err);
    alert("Gagal memindahkan item. Silakan coba lagi.");
  }
};

// --- ambil data
const refreshData = async () => {
  try {
    const [itemRes, trayRes] = await Promise.all([
      axios.get("/api/item", {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      }),
      axios.get("/api/nampan", {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      }),
    ]);
    items.value = itemRes.data;
    trays.value = trayRes.data;
  } catch (err) {
    error.value = err.message || "Gagal mengambil data";
  } finally {
    loading.value = false;
  }
};

onMounted(refreshData);

const filteredItems = computed(() => {
  if (!props.search) return items.value;
  return items.value.filter((item) =>
    item.produk?.nama?.toLowerCase().includes(props.search.toLowerCase())
  );
});
</script>
