<template>
  <section class="container-page py-10">
    <div class="mb-8">
      <h1 class="text-3xl font-extrabold">Marketplace</h1>
      <p class="mt-2 text-slate-600">Cari barang bekas teknologi sesuai kebutuhanmu.</p>
    </div>

    <div class="card mb-8 grid gap-4 p-4 lg:grid-cols-4">
      <input v-model="search" class="input lg:col-span-2" placeholder="Cari laptop, router, server..." />

      <select v-model="selectedCategory" class="input">
        <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
      </select>

      <select v-model="selectedCondition" class="input">
        <option value="Semua">Semua Kondisi</option>
        <option value="Bekas Normal">Bekas Normal</option>
        <option value="Bekas Mulus">Bekas Mulus</option>
        <option value="Bekas Server Room">Bekas Server Room</option>
      </select>
    </div>

    <div class="mb-5 flex items-center justify-between">
      <p class="text-sm font-semibold text-slate-600">
        {{ loading ? "Memuat produk..." : `Menampilkan ${filteredProducts.length} produk` }}
      </p>
      <RouterLink to="/jual" class="btn-primary !px-4 !py-2">+ Jual Barang</RouterLink>
    </div>

    <p v-if="errorMessage" class="mb-5 rounded-xl bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-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="filteredProducts.length" class="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
      <ProductCard
        v-for="product in filteredProducts"
        :key="product.id"
        :product="product"
        :saved="saved.includes(product.id)"
        @toggle-save="toggleSave"
      />
    </div>

    <div v-else class="card p-10 text-center">
      <h2 class="text-xl font-extrabold">Produk tidak ditemukan</h2>
      <p class="mt-2 text-slate-600">Coba ganti keyword atau filter kategori.</p>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from "vue"
import ProductCard from "../components/ProductCard.vue"
import { products as defaultProducts, categories } from "../data/products"
import { fetchProducts, getSavedProducts, setSavedProducts } from "../utils"

const search = ref("")
const selectedCategory = ref("Semua")
const selectedCondition = ref("Semua")
const saved = ref(getSavedProducts())
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) {
    products.value = defaultProducts
    errorMessage.value = "Backend belum bisa dihubungi, jadi sementara menampilkan data contoh."
  } finally {
    loading.value = false
  }
}

const filteredProducts = computed(() => {
  return products.value.filter((product) => {
    const keyword = search.value.toLowerCase()
    const matchSearch =
      product.title.toLowerCase().includes(keyword) ||
      product.description.toLowerCase().includes(keyword) ||
      product.category.toLowerCase().includes(keyword)

    const matchCategory =
      selectedCategory.value === "Semua" || product.category === selectedCategory.value

    const matchCondition =
      selectedCondition.value === "Semua" || product.condition === selectedCondition.value

    const matchStatus = product.status === "Tersedia" || !product.status

    return matchSearch && matchCategory && matchCondition && matchStatus
  })
})

function toggleSave(id) {
  if (saved.value.includes(id)) {
    saved.value = saved.value.filter((item) => item !== id)
  } else {
    saved.value.push(id)
  }
  setSavedProducts(saved.value)
}

onMounted(loadProducts)
</script>
