<script setup lang="ts">
import { onMounted, ref } from "vue";
import BrowsingHistoryList from "./components/BrowsingHistoryList.vue";
import HistoryToolbar from "./components/HistoryToolbar.vue";
import * as browsingHistoryService from "@/services/browsingHistory.service"
import type { BrowsingHistories } from "@/types/browsingHistory.types";
import SpinComponent from "@/components/SpinComponent.vue";

const histories = ref<BrowsingHistories | null>(null);

const currentPage = ref(1);

const page = ref(1);

const filterValue = ref('3');

const loading = ref(false)

function fetchBrowsing() {
  loading.value = true
  browsingHistoryService.fetch(page.value, parseInt(filterValue.value)).then((resp) => {
    histories.value = resp;
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleDelete(id: number) {
  loading.value = true
  browsingHistoryService.remove(id).then(() => {
    fetchBrowsing()
  })
}

function onfilterChange(value: string) {
  filterValue.value = value
  fetchBrowsing()
}

function ondeleteAll() {
  loading.value = true
  browsingHistoryService.removeAll().then(() => {
    fetchBrowsing()
  })
}

function onPaginationChange(p: number) {
  page.value = p
  fetchBrowsing()
}

onMounted(() => {
  fetchBrowsing();
});
</script>

<template>
  <HistoryToolbar @filterChange="onfilterChange" @deleteAll="ondeleteAll" />
  <SpinComponent :spinning="loading">
    <BrowsingHistoryList v-if="histories" :data="histories.items" @delete="handleDelete" class="history-list-wrap" />
  </SpinComponent>
  <div class="pagination">
    <a-pagination v-model:current="currentPage" :total="histories?.total" @change="onPaginationChange" />
  </div>
</template>

<style scoped lang="scss">
.history-list-wrap {
  margin-top: 16px;
}

.pagination {
  margin-top: 16px;
  text-align: right;

  :deep(.ant-pagination) {
    height: 32px;
  }
}
</style>
