<template>
  <aside class="card p-4">
    <div class="mb-6">
      <p class="text-xs font-bold uppercase tracking-wider text-slate-500">
        Menu User
      </p>
      <h2 class="mt-1 text-lg font-extrabold">Dashboard</h2>

      <div v-if="currentUser" class="mt-4 rounded-xl bg-slate-50 p-3">
        <p class="text-sm font-bold text-slate-800">
          {{ currentUser.name }}
        </p>
        <p class="mt-1 text-xs text-slate-500">
          {{ currentUser.email }}
        </p>
        <p
          v-if="isSuperadmin"
          class="mt-2 inline-flex rounded-full bg-red-50 px-3 py-1 text-xs font-bold text-red-700"
        >
          Superadmin
        </p>
      </div>
    </div>

    <nav class="grid gap-2">
      <RouterLink class="side-link" to="/dashboard">
        <LayoutDashboard size="18" />
        Barang Saya
      </RouterLink>

      <RouterLink class="side-link" to="/jual">
        <PlusCircle size="18" />
        Jual Barang
      </RouterLink>

      <RouterLink class="side-link" to="/marketplace">
        <Store size="18" />
        Marketplace
      </RouterLink>

      <RouterLink class="side-link" to="/tersimpan">
        <Heart size="18" />
        Barang Tersimpan
      </RouterLink>

      <RouterLink
        v-if="isSuperadmin"
        class="side-link admin-link"
        to="/admin/products"
      >
        <ShieldCheck size="18" />
        Admin Marketplace
      </RouterLink>

      <button class="side-link text-left" type="button" @click="logout">
        <LogOut size="18" />
        Logout
      </button>
    </nav>
  </aside>
</template>

<script setup>
import { computed, onMounted, ref, watch } from "vue"
import { useRoute, useRouter } from "vue-router"
import {
  Heart,
  LayoutDashboard,
  LogOut,
  PlusCircle,
  ShieldCheck,
  Store
} from "lucide-vue-next"
import { clearAuth, fetchCurrentUser, getCurrentUser, getToken, setAuth } from "../utils"

const router = useRouter()
const route = useRoute()
const currentUser = ref(getCurrentUser())

const isSuperadmin = computed(() => {
  return currentUser.value?.role === "superadmin"
})

watch(
  () => route.fullPath,
  () => {
    currentUser.value = getCurrentUser()
  }
)

async function refreshCurrentUser() {
  if (!getToken()) return

  try {
    const data = await fetchCurrentUser()
    setAuth({
      token: getToken(),
      user: data.user
    })
    currentUser.value = getCurrentUser()
  } catch {
    clearAuth()
    currentUser.value = null
  }
}

function logout() {
  clearAuth()
  router.push("/login")
}

onMounted(refreshCurrentUser)
</script>

<style scoped>
.side-link {
  @apply flex w-full items-center gap-3 rounded-xl px-3 py-3 text-sm font-semibold text-slate-700 transition hover:bg-slate-100;
}

.admin-link {
  @apply bg-red-50 text-red-700 hover:bg-red-100;
}

.router-link-active {
  @apply bg-brand-50 text-brand-700;
}
</style>
