<template>
  <section class="container-page py-10">
    <div class="mb-8">
      <h1 class="text-3xl font-extrabold">Admin Marketplace</h1>
      <p class="mt-2 text-slate-600">Kelola semua produk yang tampil di marketplace.</p>
    </div>

    <p v-if="errorMessage" class="mb-5 rounded-xl bg-red-50 px-4 py-3 text-sm font-semibold text-red-700">
      {{ errorMessage }}
    </p>

    <div v-if="loading" class="card p-10 text-center">
      <h2 class="text-xl font-extrabold">Memuat produk...</h2>
    </div>

    <div v-else-if="products.length" class="grid gap-4">
      <div
        v-for="product in products"
        :key="product.id"
        class="card grid gap-4 p-4 md:grid-cols-[140px_1fr_auto] md:items-center"
      >
        <img
          :src="getProductImageUrl(product.image)"
          :alt="product.title"
          class="aspect-[4/3] w-full rounded-xl object-cover md:w-36"
        />

        <div>
          <div class="flex flex-wrap items-center gap-2">
            <span class="rounded-full bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700">
              {{ product.category }}
            </span>
            <span class="rounded-full bg-emerald-50 px-3 py-1 text-xs font-bold text-emerald-700">
              {{ product.status }}
            </span>
          </div>

          <h3 class="mt-3 font-extrabold">{{ product.title }}</h3>
          <p class="mt-1 text-sm text-slate-500">
            {{ product.seller }} • {{ product.location }} • {{ product.condition }}
          </p>
          <p class="mt-2 font-extrabold text-brand-700">
            {{ formatRupiah(product.price) }}
          </p>
        </div>

        <div class="flex flex-wrap gap-2 md:flex-col">
          <RouterLink :to="`/produk/${product.id}`" class="btn-secondary !px-3 !py-2">
            Detail
          </RouterLink>
          <button
            class="rounded-xl bg-red-50 px-3 py-2 text-sm font-bold text-red-700 hover:bg-red-100"
            @click="deleteAsAdmin(product.id)"
          >
            Hapus
          </button>
        </div>
      </div>
    </div>

    <div v-else class="card p-10 text-center">
      <h2 class="text-xl font-extrabold">Belum ada produk</h2>
    </div>
  </section>
</template>

<script setup>
import { onMounted, ref } from "vue"
import { API_BASE_URL, fetchProducts, formatRupiah, getProductImageUrl, getToken } from "../utils"

const products = ref([])
const loading = ref(true)
const errorMessage = ref("")

async function loadProducts() {
  loading.value = true
  errorMessage.value = ""

  try {
    const data = await fetchProducts()
    products.value = data.products
  } catch (error) {
    errorMessage.value = error.message
  } finally {
    loading.value = false
  }
}

async function deleteAsAdmin(id) {
  if (!confirm("Yakin ingin menghapus produk ini dari marketplace?")) return

  try {
    const response = await fetch(`${API_BASE_URL}/api/admin/products/${id}`, {
      method: "DELETE",
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })

    const data = await response.json().catch(() => ({}))

    if (!response.ok) {
      throw new Error(data.message || "Gagal menghapus produk.")
    }

    products.value = products.value.filter((product) => product.id !== id)
  } catch (error) {
    errorMessage.value = error.message
  }
}

onMounted(loadProducts)
</script>
