<template>
  <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>
    <!-- Alert Section -->
    <div class="mb-4" v-if="alert">
      <div v-if="alert.error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
        <strong class="font-bold">Error!</strong>
        <span class="block sm:inline">{{ alert.error }}</span>
      </div>
      <div v-if="alert.success" class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
        <strong class="font-bold">Success!</strong>
        <span class="block sm:inline">{{ alert.success }}</span>
      </div>
    </div>

    <!-- Statistik Brankas -->
    <div class="bg-A border border-C rounded-xl p-4 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-archive text-D"></i>
          </div>
          <div class="flex flex-col sm:flex-row sm:gap-6 text-sm text-gray-600">
            <span>Total Item di brankas: {{ filteredItems.length }}</span>
          </div>
        </div>
        <div class="text-right">
          <div class="text-2xl font-bold text-D">{{ totalWeight }}g</div>
          <div class="text-sm text-gray-500">Total Berat</div>
        </div>
      </div>
    </div>

    <!-- Daftar Item -->
    <div v-if="filteredItems.length === 0" class="text-center text-gray-500 py-[120px]">
      {{ props.search ? 'Item tidak ditemukan.' : 'Brankas kosong.' }}
    </div>

    <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="item in filteredItems" :key="item.id"
        class="flex justify-between items-center border border-C 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-cover rounded" 
               @error="handleImageError" />
          <div class="size-12 bg-gray-200 rounded flex items-center justify-center" v-else>
            <i class="fas fa-image text-gray-400"></i>
          </div>
          <div>
            <p class="font-semibold text-D">{{ item.produk?.nama }}</p>
            <p class="text-sm text-gray-500 font-semibold">{{ item.kode_item }}</p>
          </div>
        </div>

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

    <!-- Modal Pindah Nampan -->
    <div v-if="isPopupVisible" class="fixed inset-0 bg-black/75 flex items-center justify-center p-4 z-50 backdrop-blur-sm">
      <div class="bg-white rounded-xl shadow-lg max-w-sm w-full p-6 relative transform transition-all duration-300 scale-95 opacity-0 animate-fadeIn">
        <!-- QR Code -->
        <div class="flex justify-center mb-4">
          <div class="p-2 border border-C rounded-lg">
            <img :src="qrCodeUrl" alt="QR Code" class="size-36" />
          </div>
        </div>

        <!-- Info Produk -->
        <div class="text-center text-D font-bold text-lg mb-1">
          {{ selectedItem?.kode_item }}
        </div>
        <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>

        <!-- Tombol Cetak -->
        <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 pilih nampan -->
        <div class="mb-4">
          <label for="tray-select" class="block text-sm font-medium text-D mb-2">
            Pindah ke Nampan
          </label>
          <select id="tray-select" v-model="selectedTrayId"
            class="w-full px-3 py-2 border border-C rounded-md shadow-sm focus:border-D focus:ring focus:ring-D/20 focus:ring-opacity-50">
            <option value="" disabled>Pilih Nampan</option>
            <option v-for="tray in trays" :key="tray.id" :value="tray.id">
              {{ tray.nama }}
            </option>
          </select>
          <p v-if="errorMove" class="text-red-500 text-sm mt-1">{{ errorMove }}</p>
        </div>

        <!-- Tombol -->
        <!-- Tombol -->
<div class="flex justify-end gap-2">
  <button @click="closePopup" class="px-4 py-2 rounded border border-gray-300 text-gray-700 hover:bg-gray-50 transition">
    Batal
  </button>

<button @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 @click="saveMove" :disabled="!selectedTrayId || isMoving" 
          class="px-4 py-2 rounded text-D transition flex items-center"
          :class="(selectedTrayId && !isMoving) ? 'bg-C hover:bg-C/80' : 'bg-gray-400 cursor-not-allowed'">
    <div v-if="isMoving" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
    {{ isMoving ? 'Memindahkan...' : 'Pindahkan' }}
  </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"
    />

    <!-- Confirm Modal untuk aksi berbahaya (jika diperlukan di masa depan) -->
    <div v-if="isConfirmModalVisible" class="fixed inset-0 bg-black/75 flex items-center justify-center p-4 z-50 backdrop-blur-sm">
      <div class="bg-white rounded-xl shadow-lg max-w-md w-full p-6 transform transition-all duration-300 scale-95 opacity-0 animate-fadeIn">
        <div class="flex items-center mb-4">
          <div class="flex-shrink-0 w-10 h-10 mx-auto bg-red-100 rounded-full flex items-center justify-center">
            <i class="fas fa-exclamation-triangle text-red-600"></i>
          </div>
          <div class="ml-3">
            <h3 class="text-lg font-medium text-D">{{ confirmModalTitle }}</h3>
          </div>
        </div>
        <div class="mb-4">
          <p class="text-sm text-gray-500" v-html="confirmModalMessage"></p>
        </div>
        <div class="flex justify-end gap-2">
          <button @click="closeConfirmModal" class="px-4 py-2 rounded border border-gray-300 text-gray-700 hover:bg-gray-50 transition">
            {{ cancelText }}
          </button>
          <button @click="handleConfirmAction" class="px-4 py-2 rounded bg-red-500 hover:bg-red-600 text-white transition">
            {{ confirmText }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

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

// State modal pindah
const isPopupVisible = ref(false);
const selectedItem = ref(null);
const selectedTrayId = ref("");
const errorMove = ref("");
const isMoving = ref(false);

const showDeleteConfirm = ref(false);

// State modal konfirmasi
const isConfirmModalVisible = ref(false);
const confirmModalTitle = ref("");
const confirmModalMessage = ref("");
const confirmText = ref("Ya, Konfirmasi");
const cancelText = ref("Batal");

// 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 "";
});

// Computed untuk statistik
const totalWeight = computed(() => {
  const total = filteredItems.value.reduce((sum, item) => {
    return sum + (item?.produk?.berat || 0);
  }, 0);
  return total.toFixed(2);
});

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

// Fungsi modal pindah
const openMovePopup = (item) => {
  selectedItem.value = item;
  selectedTrayId.value = "";
  errorMove.value = "";
  isPopupVisible.value = true;
};

const closePopup = () => {
  isPopupVisible.value = false;
  selectedItem.value = null;
  selectedTrayId.value = "";
  errorMove.value = "";
  isMoving.value = false;
};

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

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

    // Tampilkan alert sukses
    alert.value = { success: `Item ${selectedItem.value.kode_item} berhasil dihapus.` };

    // Refresh data
    await refreshData();

    // Tutup modal & popup
    showDeleteConfirm.value = false;
    closePopup();

    // Auto hide alert
    clearTimeout(timer.value);
    timer.value = setTimeout(() => { alert.value = null; }, 3000);

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

    // Auto hide alert error
    clearTimeout(timer.value);
    timer.value = setTimeout(() => { alert.value = null; }, 5000);
  }
};


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

const saveMove = async () => {
  if (!selectedTrayId.value || !selectedItem.value || isMoving.value) return;
  
  errorMove.value = "";
  isMoving.value = true;
  
  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")}` },
      }
    );

    // Tampilkan alert sukses
    const trayName = trays.value.find(t => t.id === selectedTrayId.value)?.nama;
    alert.value = { success: `Item berhasil dipindahkan ke nampan "${trayName}"` };
    
    await refreshData();
    closePopup();
    
    // Auto hide alert
    clearTimeout(timer.value);
    timer.value = setTimeout(() => { alert.value = null; }, 3000);
    
  } catch (err) {
    console.error("Gagal memindahkan item:", err.response?.data || err);
    errorMove.value = err.response?.data?.message || "Gagal memindahkan item. Silakan coba lagi.";
  } finally {
    isMoving.value = false;
  }
};

// Fungsi modal konfirmasi
const closeConfirmModal = () => {
  isConfirmModalVisible.value = false;
  confirmModalTitle.value = "";
  confirmModalMessage.value = "";
  confirmText.value = "Ya, Konfirmasi";
  cancelText.value = "Batal";
};

const handleConfirmAction = async () => {
  // Implementasi aksi konfirmasi jika diperlukan
  closeConfirmModal();
};

// Fungsi utilitas
const printQR = () => {
  if (qrCodeUrl.value) {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>Print QR Code - ${selectedItem.value.kode_item}</title>
          <style>
            body { 
              font-family: Arial, sans-serif; 
              text-align: center; 
              padding: 20px; 
            }
            .qr-container { 
              border: 2px solid #ccc; 
              padding: 20px; 
              display: inline-block; 
              margin: 20px;
            }
            .item-info {
              margin-top: 10px;
              font-size: 14px;
            }
          </style>
        </head>
        <body>
          <div class="qr-container">
            <img src="${qrCodeUrl.value}" alt="QR Code" style="width: 200px; height: 200px;" />
            <div class="item-info">
              <div style="font-weight: bold; margin-bottom: 5px;">${selectedItem.value.kode_item}</div>
              <div>${selectedItem.value.produk.nama}</div>
              <div style="color: #666; margin-top: 5px;">${selectedItem.value.produk.berat}g</div>
            </div>
          </div>
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  }
};

const handleImageError = (event) => {
  event.target.style.display = 'none';
};

// 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")}` },
      }),
    ]);
    
    // Filter hanya item yang ada di brankas (id_nampan = null atau tidak ada)
    items.value = itemRes.data.filter(item => !item.id_nampan);
    trays.value = trayRes.data; 
  } catch (err) {
    console.error("Error fetching data:", err);
    alert.value = { error: err.response?.data?.message || "Gagal mengambil data" };
    clearTimeout(timer.value);
    timer.value = setTimeout(() => { alert.value = null; }, 5000);
  } finally {
    loading.value = false;
  }
};

onMounted(refreshData);
</script>

<style scoped>
@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}
.animate-fadeIn {
  animation: fadeIn 0.25s ease-out forwards;
}
</style>
