<template>
  <section class="container-page py-10">
    <div class="grid gap-8 lg:grid-cols-[280px_1fr]">
      <DashboardSidebar />

      <div>
        <div class="mb-8">
          <h1 class="text-3xl font-extrabold">Barang Saya</h1>
          <p class="mt-2 text-slate-600">Kelola barang yang kamu posting ke database.</p>
        </div>

        <div class="mb-8 grid gap-4 sm:grid-cols-3">
          <div class="card p-5">
            <p class="text-sm font-semibold text-slate-500">Total Barang</p>
            <h2 class="mt-2 text-3xl font-extrabold">{{ userProducts.length }}</h2>
          </div>
          <div class="card p-5">
            <p class="text-sm font-semibold text-slate-500">Tersedia</p>
            <h2 class="mt-2 text-3xl font-extrabold">{{ availableCount }}</h2>
          </div>
          <div class="card p-5">
            <p class="text-sm font-semibold text-slate-500">Terjual</p>
            <h2 class="mt-2 text-3xl font-extrabold">{{ soldCount }}</h2>
          </div>
        </div>

        <div class="mb-5 flex items-center justify-between">
          <h2 class="text-xl font-extrabold">Management Barang</h2>
          <RouterLink to="/jual" class="btn-primary !px-4 !py-2">+ Tambah Barang</RouterLink>
        </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 barang...</h2>
        </div>

        <div v-else-if="userProducts.length" class="grid gap-4">
          <div v-for="product in userProducts" :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 || "Tersedia" }}</span>
              </div>
              <h3 class="mt-3 font-extrabold">{{ product.title }}</h3>
              <p class="mt-1 text-sm text-slate-500">{{ 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="btn-secondary !px-3 !py-2" @click="markSold(product.id)">Tandai Terjual</button>
              <button class="rounded-xl bg-red-50 px-3 py-2 text-sm font-bold text-red-700 hover:bg-red-100" @click="deleteProduct(product.id)">Hapus</button>
            </div>
          </div>
        </div>

        <div v-else class="card p-10 text-center">
          <h2 class="text-xl font-extrabold">Belum ada barang</h2>
          <p class="mt-2 text-slate-600">Coba posting barang bekas teknologi pertamamu.</p>
          <RouterLink to="/jual" class="btn-primary mt-5">Jual Barang</RouterLink>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from "vue"
import DashboardSidebar from "../components/DashboardSidebar.vue"
import { deleteProductById, fetchMyProducts, formatRupiah, getProductImageUrl, updateProductStatus } from "../utils"

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

const availableCount = computed(() => userProducts.value.filter((p) => (p.status || "Tersedia") === "Tersedia").length)
const soldCount = computed(() => userProducts.value.filter((p) => p.status === "Terjual").length)

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

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

async function markSold(id) {
  try {
    const data = await updateProductStatus(id, "Terjual")
    userProducts.value = userProducts.value.map((product) => {
      if (product.id === id) return data.product
      return product
    })
  } catch (error) {
    errorMessage.value = error.message
  }
}

async function deleteProduct(id) {
  if (!confirm("Yakin ingin menghapus barang ini?")) return

  try {
    await deleteProductById(id)
    userProducts.value = userProducts.value.filter((product) => product.id !== id)
  } catch (error) {
    errorMessage.value = error.message
  }
}

onMounted(loadProducts)
</script>
