<script setup lang="ts">
import { useTranslations } from "../composables/useTranslations";
import { decodeHtmlEntities } from "../utils/sanitize";
import Select from "./ui/Select.vue";
import SelectContent from "./ui/SelectContent.vue";
import SelectItem from "./ui/SelectItem.vue";
import SelectTrigger from "./ui/SelectTrigger.vue";
import SelectValue from "./ui/SelectValue.vue";

const { t } = useTranslations();

type PaginationLink = {
  url: string | null;
  label: string;
  active: boolean;
};

const props = defineProps<{
  links: PaginationLink[];
  from: number | null;
  to: number | null;
  total: number;
  perPage?: number;
}>();

const emit = defineEmits<{
  goToPage: [url: string | null];
  setPerPage: [n: number];
}>();
</script>

<template>
  <div
    v-if="links.length > 3 || perPage !== undefined"
    class="flex items-center justify-between border-t px-4 py-3"
  >
    <!-- Per-page selector -->
    <div class="flex items-center gap-3">
      <Select
        v-if="perPage !== undefined"
        :model-value="String(perPage)"
        @update:model-value="emit('setPerPage', parseInt($event))"
      >
        <SelectTrigger class="h-8 w-auto">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem
            v-for="n in [10, 25, 50, 100]"
            :key="n"
            :value="String(n)"
          >
            {{
              t("builder.resources.per_page", {
                count: n,
              })
            }}
          </SelectItem>
        </SelectContent>
      </Select>
      <p v-if="links.length > 3" class="text-sm text-muted-foreground">
        {{
          t("builder.resources.showing_range", {
            from: from ?? 0,
            to: to ?? 0,
            total,
          })
        }}
      </p>
    </div>

    <!-- Page links -->
    <div v-if="links.length > 3" class="flex gap-1">
      <button
        v-for="link in links"
        :key="link.label"
        :disabled="!link.url"
        :class="[
          'inline-flex h-8 min-w-[2rem] items-center justify-center rounded px-2 text-sm transition-colors',
          link.active
            ? 'bg-primary text-primary-foreground'
            : 'text-muted-foreground hover:bg-muted hover:text-foreground',
          !link.url && 'cursor-not-allowed opacity-40',
        ]"
        @click="emit('goToPage', link.url)"
      >
        {{ decodeHtmlEntities(link.label) }}
      </button>
    </div>
  </div>
</template>
