/* eslint-disable react/require-default-props */
import React from 'react'
import { View, Text, StyleSheet, Pressable } from 'react-native'
import useDebouncedValue from '../../hooks/useDebouncedValue'
import PaginationArrow from './PaginationArrow'
import { type TableTheme } from './theme'

type Props = {
  goToNextPage: () => void
  goToPreviousPage: () => void
  currentPage: number
  theme: TableTheme
  nextDisabled?: boolean
  showPageNumber?: boolean
}

const PaginationControls: React.FC<Props> = props => {
  const {
    currentPage,
    goToNextPage,
    goToPreviousPage,
    theme,
    nextDisabled = false,
    showPageNumber = false,
  } = props

  const previousEnabled = currentPage > 0
  const nextEnabled = !nextDisabled
  const nextDisabledDebounced = useDebouncedValue(nextDisabled, 100)

  const previousDisabledStyle = !previousEnabled
    ? styles.pageTouchableDisabled
    : undefined

  // We allow for some debouncing when setting the disabled style on the next button, so it doesn't flash
  // as disabled if the user is spamming the previous or next arrow.
  const nextDisabledStyle =
    !nextEnabled && nextDisabledDebounced
      ? styles.pageTouchableDisabled
      : undefined

  let currentPageView = null
  if (showPageNumber) {
    currentPageView = (
      <View style={styles.currentPage}>
        <Text style={[styles.pageText]}>{currentPage + 1}</Text>
      </View>
    )
  }

  const hitSlop = { top: 20, bottom: 20, left: 20, right: 20 }

  return (
    <View style={styles.container}>
      <Pressable
        style={[styles.pageTouchable, previousDisabledStyle]}
        disabled={!previousEnabled}
        onPress={goToPreviousPage}
        hitSlop={hitSlop}
      >
        <PaginationArrow direction="previous" theme={theme} />
      </Pressable>
      {currentPageView}
      <Pressable
        style={[styles.pageTouchable, nextDisabledStyle]}
        disabled={!nextEnabled}
        onPress={goToNextPage}
        hitSlop={hitSlop}
      >
        <PaginationArrow direction="next" theme={theme} />
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    marginLeft: 'auto',
    marginVertical: 8,
    marginRight: 16,
    display: 'flex',
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    zIndex: 10,
  },
  pageTouchable: {
    marginLeft: 8,
    minWidth: 20,
    minHeight: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  pageTouchableDisabled: {
    opacity: 0.2,
  },
  currentPage: {
    marginLeft: 16,
    marginRight: 8,
    backgroundColor: '#F5F5F5',
    borderRadius: 4,
    paddingVertical: 6,
    height: 30,
    width: 30,
  },
  pageText: {
    fontSize: 14,
    fontWeight: '500',
    textAlign: 'center',
  },
  arrow: {
    width: 20,
    height: 20,
  },
})

export default PaginationControls
