<template>
  <q-card class="q-pa-md" flat bordered>
    <q-table
      :key="key + '-' + pagination.perPage"
      :title="title"
      :rows="rows"
      :columns="columns"
      :row-key="rowKey"
      :loading="loading"
      :pagination="{ rowsPerPage: pagination.perPage, page: pagination.page }"
      :rows-per-page-options="[10, 25, 50, 100]"
      flat
      bordered
      hide-pagination
    >
      <template v-slot:loading>
        <q-inner-loading showing color="primary" />
      </template>

      <template v-slot:no-data>
        <slot name="no-data" />
      </template>
    </q-table>

    <div class="row q-mt-md">
      <div class="col-2 flex items-center">
        <q-select
          filled
          v-model="pagination.perPage"
          :options="[10, 25, 50, 100]"
          emit-value
          map-options
          :disable="loading || rows.length === 0"
          @update:model-value="updatePagination({ perPage: $event })"
        />
      </div>

      <div class="col-8 flex justify-center">
        <q-pagination
          v-model="pagination.page"
          color="primary"
          size="md"
          :max="pagination.totalPages"
          :disable="loading"
          input
          @update:model-value="updatePagination({ page: $event })"
        />
      </div>

      <div class="col-2 flex justify-end items-center">
        <span class="text-grey-5">Total: {{ pagination.total }}</span>
      </div>
    </div>
  </q-card>
</template>

<script>
import has from "lodash/has";

export default {
  name: "Table",
  props: {
    key: {
      type: String,
      default: "table-clipperia",
    },
    columns: {
      type: Array,
      required: true,
      validator: (value) =>
        Array.isArray(value) &&
        value.every((col) => has(col, "name") && has(col, "label")),
    },
    rows: {
      type: Array,
      required: true,
      validator: (value) => Array.isArray(value),
    },
    rowName: {
      type: String,
      default: "name",
    },
    rowKey: {
      type: String,
      default: "id",
    },
    title: String,
    loading: {
      type: Boolean,
      default: false,
    },
    pagination: {
      type: Object,
      required: false,
      default: {
        page: 1,
        direction: "desc",
        perPage: 10,
        total: 10,
        totalPages: 1,
        hasNext: false,
        hasPrev: false,
      },
    },
  },
  emits: ["update:pagination"],
  methods: {
    updatePagination({ page, perPage }) {
      const newPagination = { ...this.pagination };

      if (page) {
        newPagination.page = page;
      }
      if (perPage) {
        newPagination.perPage = perPage;
      }

      this.$emit("update:pagination", newPagination);
    },
  },
};
</script>
