<template>
  <div class="list-paging-wrapper">
    <div class="pagination-content">
      <icon-button
        classList="pagination-nav pagination-nav-prev"
        @click="changePage('<')"
        icon="arrow" />
      <div class="pagination-input">
        <input
          type="text"
          class="pagination-current-page"
          :value="pageNumber"
          @keydown="validationStore.allowNumbersWithKeys"
          @keyup="InputPageControl($event)"
          @focus="PageNumberFocus($event)"
          min="1"
          :max="totalPage()" />
      </div>
      <div class="pagination-total-page">
        /
        <span>{{ totalPage() }}</span>
      </div>
      <div class="button-c" @click="getPage">Git</div>
      <icon-button
        classList="pagination-nav pagination-nav-next"
        @click="changePage('>')"
        icon="arrow" />
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, computed } from 'vue'
  import type { Ref } from 'vue'
  import { useGlobalStore } from '@/stores/globalStore'
  import { useValidationStore } from '@/stores/validationStore'

  const globalStore = useGlobalStore()
  const validationStore = useValidationStore()

  interface IPagination {
    pageNumber: number
    pageSize: number
    totalRecords: number
  }

  export interface Props {
    pagination: IPagination
  }

  const props = withDefaults(defineProps<Props>(), {
  })

  const emit = defineEmits(['update:pagination'])

  const localPagination: Ref<IPagination> = ref(props.pagination)
  const pageNumber: Ref<number> = ref(1)

  const totalPage = (): number => {
    return Math.ceil(localPagination.value.totalRecords / globalStore.perPage)
  }

  const changePage = (v: string) => {
    if (v === '<') {
      if (Number(pageNumber.value) > 1) pageNumber.value--
    } else {
      if (Number(pageNumber.value) < totalPage()) pageNumber.value++
    }
    localPagination.value.pageNumber = pageNumber.value
    emit('update:pagination', localPagination.value)
  }

  const InputPageControl = (e: Event) => {
    if (Number((e.target as HTMLInputElement).value) < 1)
      (e.target as HTMLInputElement).value = '1'
    if (Number((e.target as HTMLInputElement).value) > totalPage())
      (e.target as HTMLInputElement).value = String(totalPage())
    pageNumber.value = Number((e.target as HTMLInputElement).value)

    if((e as KeyboardEvent).key === 'Enter') getPage()
  }
  const PageNumberFocus = (e: Event) => {
    ;(e.target as HTMLInputElement).select()
  }
  const getPage = () => {
    localPagination.value.pageNumber = pageNumber.value
    emit('update:pagination', localPagination.value)
  }
</script>
