<template>
  <ConfirmDeleteModal v-if="showDeleteModal" :isOpen="showDeleteModal" title="Konfirmasi"
    message="Yakin ingin menghapus item ini?" @confirm="hapusPesanan" @cancel="closeDeleteModal" />

  <!-- ==== TAMBAHAN: Struk Overlay ==== -->
  <StrukOverlay v-if="showStruk" :isOpen="showStruk" :pesanan="pesanan" :total="total" @close="closeStruk" />
  <!-- ==== END TAMBAHAN ==== -->

  <div class="p-2 sm:p-4">
    <!-- Grid Form & Total -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
      <!-- Input Form -->
      <div class="order-2 md:order-1 flex flex-col gap-4">
        <!-- Input Kode Item -->
        <div>
          <label class="block text-sm font-medium text-D">Kode Item *</label>
          <div class="flex flex-row justify-between mt-1 w-full rounded-md bg-A shadow-sm sm:text-sm border-B">
            <input type="text" v-model="kodeItem" @keyup.enter="inputItem" placeholder="Scan atau masukkan kode item"
              class="bg-A focus:outline-none focus:border-C focus:ring focus:ring-D focus:ring-opacity-50 p-2 w-full rounded-l-md" />
            <button v-if="!loadingItem" @click="inputItem" class="px-3 bg-D hover:bg-D/80 text-A rounded-r-md">
              <i class="fas fa-arrow-right"></i>
            </button>
            <div v-else class="flex items-center justify-center px-3">
              <div class="rounded-full h-5 w-5 border-b-2 border-A flex items-center justify-center">
                <i class="fas fa-spinner"></i>
              </div>
            </div>
          </div>
        </div>

        <!-- Input Harga Jual -->
        <div>
          <label class="block text-sm font-medium text-D">Harga Jual</label>
          <InputField v-model="hargaJual" type="number" placeholder="Masukkan Harga Jual" />
        </div>

        <!-- Tombol Aksi -->
        <div class="flex flex-col sm:flex-row justify-between gap-2">
          <button @click="tambahItem"
            class="w-full sm:w-auto px-4 py-2 rounded-md bg-C text-D font-medium hover:bg-C/80 transition">
            Tambah Item
          </button>
          <button @click="konfirmasiPenjualan"
            class="w-full sm:w-auto px-6 py-2 rounded-md bg-D text-A font-semibold hover:bg-D/80 transition">
            Lanjut
          </button>
        </div>
      </div>

      <!-- Total -->
      <div class="order-1 md:order-2 flex flex-col md:flex-row md:items-center md:justify-center gap-1">
        <div class="text-left md:text-start">
          <span class="block text-gray-600 font-medium">Total:</span>
          <span class="text-2xl sm:text-3xl font-bold text-D">
            Rp{{ total.toLocaleString() }},-
          </span>
        </div>
      </div>
    </div>

    <!-- Error & Info -->
    <div class="mb-4">
      <p v-if="error" :class="{ 'animate-shake': error }" class="text-sm text-red-600 mt-1">
        {{ error }}
      </p>
      <p v-if="info" class="text-sm text-C mt-1">{{ info }}</p>
    </div>

    <!-- Table Responsive -->
    <div class="overflow-x-auto">
      <table class="w-full border border-B rounded-lg overflow-hidden text-xs sm:text-sm">
        <thead class="bg-A text-D">
          <tr>
            <th class="border border-B p-2 w-8">No</th>
            <th class="border border-B p-2">Nama Produk</th>
            <th class="border border-B p-2">Posisi</th>
            <th class="border border-B p-2">Harga</th>
            <th class="border border-B p-2 w-10"></th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="pesanan.length == 0" class="text-center text-D/70">
            <td colspan="5" class="h-16 border border-B text-xs sm:text-sm">
              Belum ada item dipesan
            </td>
          </tr>
          <tr v-else v-for="(item, index) in pesanan" :key="index" class="hover:bg-gray-50 text-center">
            <td class="border border-B p-2">{{ index + 1 }}</td>
            <td class="border border-B p-2 text-left truncate max-w-[120px] sm:max-w-none">
              {{ item.produk.nama }}
            </td>
            <td class="border border-B p-2 truncate max-w-[80px]">
              {{ item.nampan ? item.nampan.nama : "Brankas" }}
            </td>
            <td class="border border-B p-2 whitespace-nowrap">
              Rp{{ item.harga_deal.toLocaleString() }}
            </td>
            <td class="border border-B p-2 text-center">
              <button @click="openDeleteModal(index)" class="text-red-500 hover:text-red-700">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

  </div>
</template>


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

const kodeItem = ref("");
const info = ref("");
const error = ref("");
const hargaJual = ref(null);
const item = ref(null);
const loadingItem = ref(false);
const pesanan = ref([]);
const showDeleteModal = ref(false)
const deleteIndex = ref(null)

const showStruk = ref(false);

let errorTimeout = null;
let infoTimeout = null;

const inputItem = async () => {
  if (!kodeItem.value) return;

  info.value = "";
  error.value = "";
  clearTimeout(infoTimeout);
  clearTimeout(errorTimeout);

  loadingItem.value = true;

  try {
    const response = await axios.get(`/api/item/${kodeItem.value}`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    });
    item.value = response.data;
    hargaJual.value = item.value.produk.harga_jual;

    console.log(item.value);

    if (item.value.is_sold) {
      throw new Error("Item sudah terjual");
    }
    if (pesanan.value.some((p) => p.id === item.value.id)) {
      throw new Error("Item sedang dipesan");
    }
    info.value = `Item dipilih: ${item.value.produk.nama} dari ${item.value.nampan ? 'Nampan ' + item.value.nampan.nama : "Brankas"}`;

    infoTimeout = setTimeout(() => {
      info.value = "";
    }, 3000);
  } catch (err) {
    if (err == "") {
      error.value = "Error: Item tidak ditemukan";
    } else {
      error.value = err;
    }
    info.value = "";
    hargaJual.value = null;
    item.value = null;

    errorTimeout = setTimeout(() => {
      error.value = "";
    }, 3000);
  } finally {
    loadingItem.value = false;
  }
};

const tambahItem = () => {
  if (!item.value || !hargaJual.value) {
    error.value = "Scan atau masukkan kode item untuk dijual.";
    if (kodeItem.value) {
      error.value =
        "Masukkan harga jual, atau input dari kode item lagi.";
    }
    clearTimeout(errorTimeout);
    errorTimeout = setTimeout(() => {
      error.value = "";
    }, 3000);
    return;
  }

  // harga deal
  item.value.kode_item = Number(kodeItem.value);
  item.value.harga_deal = Number(hargaJual.value);
  item.value.posisi = item.value.nampan ? item.value.nampan.nama : "Brankas";

  pesanan.value.push(item.value);

  // Reset input fields
  kodeItem.value = "";
  hargaJual.value = null;
  item.value = null;
  info.value = "";
  clearTimeout(infoTimeout);
};

const openDeleteModal = (index) => {
  deleteIndex.value = index
  showDeleteModal.value = true
}

const closeDeleteModal = () => {
  showDeleteModal.value = false
  deleteIndex.value = null
}

const hapusPesanan = () => {
  if (deleteIndex.value !== null) {
    pesanan.value.splice(deleteIndex.value, 1)
  }
  closeDeleteModal()
}

// ==== MODIFIKASI: konfirmasiPenjualan sekarang menampilkan struk ====
const konfirmasiPenjualan = () => {
  if (pesanan.value.length === 0) {
    error.value = "Belum ada item yang dipesan.";
    clearTimeout(errorTimeout);
    errorTimeout = setTimeout(() => {
      error.value = "";
    }, 3000);
    return;
  }

  // Tampilkan struk overlay
  showStruk.value = true;
};
// ==== END MODIFIKASI ====

// ==== TAMBAHAN: Fungsi untuk menutup struk ====
const closeStruk = () => {
  showStruk.value = false;
};
// ==== END TAMBAHAN ====

const total = computed(() => {
  let sum = 0;
  pesanan.value.forEach((item) => {
    sum += item.harga_deal;
  });
  return sum;
});
</script>
