<template>
  <div>
    <!-- Tampilkan berat rata-rata -->
    <div class="bg-A border border-C rounded-xl p-4 mx-6 mb-6">
      <div class="flex flex-row sm:items-center justify-between gap-4">
        <div class="flex items-center gap-3">
          <div class="p-2 bg-A rounded-lg">
            <i class="fas fa-weight text-D"></i>
          </div>
          <div class="flex flex-col sm:flex-row sm:gap-6 text-sm text-gray-600">
            <span>Total: {{ totalTrays }}</span>
            <span>Berisi: {{ nonEmptyTrays }}</span>
            <span>Kosong: {{ emptyTrays }}</span>
          </div>
        </div>
        <div class="text-right">
          <div class="text-2xl font-bold text-D">{{ averageWeight }}g</div>
          <div class="text-sm text-gray-500">Rata-rata</div>
        </div>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center items-center h-screen">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-C"></div>
      <span class="ml-2 text-gray-600">Memuat data...</span>
    </div>

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

    <div v-else-if="filteredTrays.length === 0" class="text-center text-gray-500 py-[120px]">
      Nampan tidak ditemukan.
    </div>

    <!-- Grid Card -->
    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 items-stretch px-6">
      <div v-for="tray in filteredTrays" :key="tray.id"
        class="border border-C rounded-xl p-4 shadow-sm hover:shadow-md transition flex flex-col h-full">
        <!-- Header Card -->
        <div class="flex justify-between items-center mb-3">
          <h2 class="font-bold text-lg text-[#102C57]">{{ tray.nama }}</h2>
          <div class="flex gap-2" v-if="isAdmin">
            <button class="p-1 rounded" @click="emit('edit', tray)">
              <i class="fa fa-pen fa-sm text-yellow-500 hover:text-yellow-600"></i>
            </button>
            <button class="p-1 rounded" @click="emit('delete', tray)">
              <i class="fa fa-trash fa-sm text-red-500 hover:text-red-600"></i>
            </button>
          </div>
        </div>

        <!-- Isi Card (Max tinggi 3 item + scroll kalau lebih) -->
        <div v-if="tray.items && tray.items.length" class="space-y-2 flex-1 overflow-y-auto max-h-[168px] pr-1">
          <div v-for="item in tray.items" :key="item.id"
            class="flex justify-between items-center border border-C rounded-lg p-2 cursor-pointer hover:bg-gray-50"
            @click="openMovePopup(item)">
            <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="size-12 object-cover rounded" />
              <div class="text-D">
                <p class="text-sm">{{ item.produk?.nama }}</p>
                <p class="text-sm font-medium">{{ item.kode_item }}</p>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <span class="font-medium">{{ item.produk?.berat }}g</span>
            </div>
          </div>
        </div>

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

        <!-- Footer Card -->
        <div class="border-t border-C mt-3 pt-2 text-right font-semibold">
          <div class="flex justify-between items-center">
            <span class="text-sm text-gray-500">{{ tray.items?.length || 0 }} item</span>
            <span class="text-lg">Berat Total: {{ totalWeight(tray) }}g</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Pop-up pindah item -->
    <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">
        <div class="flex justify-center mb-2">
          <div class="p-2 border rounded-lg">
            <img :src="barcodeUrl" alt="Barcode" class="w-64 h-24" />
          </div>
        </div>

        <div class="text-center text-D font-bold text-lg">
          {{ selectedItem.kode_item }}
        </div>
        <div class="text-center text-gray-700 font-medium mb-3">
          {{ selectedItem.produk.nama }}
        </div>

        <div class="flex justify-center mb-4">
          <button @click="printQR" class="bg-D text-A px-4 py-2 rounded hover:bg-D/80 transition">
            <i class="fas fa-print mr-2"></i>Cetak
          </button>
        </div>

        <!-- Dropdown -->
        <div class="mb-4">
          <label for="tray-select" class="block text-sm font-medium mb-1">Nama Nampan</label>
          <InputSelect v-if="isAdmin" v-model="selectedTrayId"
            :options="trays.map(tray => ({ label: tray.nama, value: tray.id }))" placeholder="Pilih Nampan"
            class="mt-2" />
          <div class="bg-A px-3 py-2 rounded text-D font-medium" v-else>
            {{trays.find(tray => tray.id === selectedTrayId)?.nama}}
          </div>
        </div>

        <div class="flex justify-end gap-2">
            <button @click="closePopup" class="px-4 py-2 rounded bg-gray-400 hover:bg-gray-500 text-white transition">
                {{ isAdmin ? 'Batal' : 'Tutup' }}
            </button>

            <!-- Tombol Hapus hanya muncul kalau Admin -->
            <button v-if="isAdmin" @click="showDeleteConfirm = true"
                class="px-4 py-2 rounded bg-red-500 text-white hover:bg-red-600 transition flex items-center">
                <i class="fas fa-trash mr-2"></i>Hapus
            </button>

            <button v-if="isAdmin" @click="saveMove" :disabled="!selectedTrayId" class="px-4 py-2 rounded transition"
                :class="selectedTrayId ? 'bg-C hover:bg-C/80 text-D' : 'bg-gray-400 cursor-not-allowed'">
                Simpan
            </button>
        </div>

      </div>
    </div>

    <!-- Modal Konfirmasi Hapus -->
    <ConfirmDeleteModal :isOpen="showDeleteConfirm" title="Konfirmasi Hapus Item"
      message="Apakah kamu yakin ingin menghapus item ini?" confirmText="Ya, Hapus" cancelText="Batal"
      @confirm="confirmDelete" @cancel="cancelDelete" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import InputSelect from "./InputSelect.vue";
import ConfirmDeleteModal from './ConfirmDeleteModal.vue';

const isAdmin = localStorage.getItem("role") === "owner";

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

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

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

// --- State Pop-up ---
const isPopupVisible = ref(false);
const selectedItem = ref(null);
const selectedTrayId = ref("");
const showDeleteConfirm = ref(false);

// Barcode generator (Code128)
const barcodeUrl = computed(() => {
  if (selectedItem.value) {
    const data = selectedItem.value.kode_item;
    return `https://barcode.tec-it.com/barcode.ashx?data=${encodeURIComponent(data)}&code=Code128&dpi=96`;
  }
  return "";
});

const printQR = () => {
  if (barcodeUrl.value) {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>Print Barcode - ${selectedItem.value.kode_item}</title>
          <style>
            @page {
              size: 80mm 40mm;
              margin: 1mm;
            }
            * {
              margin: 0;
              padding: 0;
            }
            body {
              font-family: Arial, sans-serif;
              display: flex;
              align-items: center;
              justify-content: center;
              height: 100vh;
              width: 100vw;
            }
            .barcode-container {
              text-align: center;
              width: 100%;
            }
            .barcode-img {
              width: 70mm;
              height: 25mm;
              margin-bottom: 2mm;
            }
            .kode-item {
              font-weight: bold;
              font-size: 14pt;
            }
          </style>
        </head>
        <body>
          <div class="barcode-container">
            <img id="barcode-img" class="barcode-img" src="${barcodeUrl.value}" alt="Barcode" />
            <div class="kode-item">${selectedItem.value.kode_item}</div>
          </div>
        </body>
      </html>
    `);

    printWindow.document.close();

    const img = printWindow.document.getElementById("barcode-img");
    img.onload = () => {
      printWindow.focus();
      printWindow.print();
    };
  }
};

const confirmDelete = async () => {
  if (!selectedItem.value) return;

  try {
    await axios.delete(`/api/item/${selectedItem.value.id}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    });

    await refreshData();
    showDeleteConfirm.value = false;
    closePopup();
  } catch (err) {
    console.error("Gagal menghapus item:", err.response?.data || err);
    error.value = err.response?.data?.message || "Gagal menghapus item. Silakan coba lagi.";
  }
};

const cancelDelete = () => {
  showDeleteConfirm.value = false;
};

// --- Fungsi Pop-up ---
const openMovePopup = (item) => {
  selectedItem.value = item;
  selectedTrayId.value = item.id_nampan;
  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);
    error.value = err.response?.data?.message || "Gagal memindahkan item. Silakan coba lagi.";
  }
};

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

// Computed untuk statistik berat rata-rata
const averageWeight = computed(() => {
  const nonEmptyTraysData = trays.value.filter(tray => {
    const weight = parseFloat(totalWeight(tray));
    return weight > 0;
  });

  if (nonEmptyTraysData.length === 0) return "0.00";

  const totalWeightSum = nonEmptyTraysData.reduce((sum, tray) => {
    return sum + parseFloat(totalWeight(tray));
  }, 0);

  const average = totalWeightSum / nonEmptyTraysData.length;
  return average.toFixed(2);
});

// Computed untuk statistik tambahan
const totalTrays = computed(() => trays.value.length);

const nonEmptyTrays = computed(() => {
  return trays.value.filter(tray => parseFloat(totalWeight(tray)) > 0).length;
});

const emptyTrays = computed(() => {
  return trays.value.filter(tray => parseFloat(totalWeight(tray)) === 0).length;
});

// Ambil data nampan + item
const refreshData = async () => {
  try {
    const nampanRes = await axios.get("/api/nampan", {
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    });
    trays.value = nampanRes.data;
  } catch (err) {
    error.value = err.message || "Gagal mengambil data";
  } finally {
    loading.value = false;
  }
};

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

onMounted(() => {
  refreshData();
});

// Expose refreshData to parent
defineExpose({ refreshData });
</script>
