'use client'

import * as React from 'react'
import type { Table } from '@tanstack/react-table'
import { ProgressiveBlur } from '@admin/components/custom/progressive-blur'
import { Button } from '@admin/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@admin/components/ui/select'
import { cn } from '@admin/utils/shared/cn'

const PAGE_SIZE_OPTIONS = [
  { value: '10', label: '10' },
  { value: '20', label: '20' },
  { value: '50', label: '50' },
  { value: '100', label: '100' },
  { value: 'all', label: 'All' }
]

interface DataTablePaginationBaseProps<TData> {
  table: Table<TData>
  pageSize: number
  setPageSize: (value: number | null) => void
  className?: string
}

interface ControlledDataTablePaginationProps {
  paginationMode: 'controlled'
  pageIndex: number
  pageCount: number
  setPageIndex: (value: number) => void
}

interface UncontrolledDataTablePaginationProps {
  paginationMode: 'uncontrolled'
  pageIndex?: never
  pageCount?: never
  setPageIndex?: never
}

type DataTablePaginationProps<TData> = DataTablePaginationBaseProps<TData> &
  (ControlledDataTablePaginationProps | UncontrolledDataTablePaginationProps)

export function DataTablePagination<TData>(props: DataTablePaginationProps<TData>) {
  const { table, pageSize, setPageSize, className } = props
  const controlledSetPageIndex =
    props.paginationMode === 'controlled' ? props.setPageIndex : undefined
  const resolvedPageIndex =
    props.paginationMode === 'controlled' ? props.pageIndex : table.getState().pagination.pageIndex
  const resolvedPageCount =
    (props.paginationMode === 'controlled' ? props.pageCount : table.getPageCount()) || 1
  const canGoPrevious = resolvedPageIndex > 0
  const canGoNext = resolvedPageIndex < resolvedPageCount - 1

  const updatePageIndex = React.useCallback(
    (nextPageIndex: number) => {
      React.startTransition(() => {
        if (controlledSetPageIndex) {
          controlledSetPageIndex(nextPageIndex)
        } else {
          table.setPageIndex(nextPageIndex)
        }
      })
    },
    [controlledSetPageIndex, table]
  )

  const handlePageSizeChange = React.useCallback(
    (value: string | null) => {
      if (value === null) return

      React.startTransition(() => {
        if (value === 'all') {
          setPageSize(-1)
        } else {
          setPageSize(Number(value))
        }
        if (controlledSetPageIndex) {
          controlledSetPageIndex(0)
        } else {
          table.setPageIndex(0)
        }
      })
    },
    [controlledSetPageIndex, setPageSize, table]
  )

  return (
    <div
      className={cn(
        'pointer-events-none fixed right-0 bottom-0 left-[var(--admin-shell-content-left)] isolate z-10 flex flex-col transition-[left] duration-200 ease-linear',
        className
      )}
    >
      <ProgressiveBlur position="bottom" height="53px" />
      <div className="pointer-events-auto flex h-(--admin-shell-bottom-bar-height) items-center justify-between border-t border-border bg-background px-4 py-2 [--admin-shell-bottom-bar-height:53px]">
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">Rows per page</span>
          <Select
            value={pageSize === -1 ? 'all' : String(pageSize)}
            onValueChange={handlePageSizeChange}
          >
            <SelectTrigger className="h-8 w-25">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {PAGE_SIZE_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            onClick={() => updatePageIndex(Math.max(resolvedPageIndex - 1, 0))}
            disabled={!canGoPrevious}
          >
            Previous
          </Button>
          <div className="text-sm text-muted-foreground">
            Page {resolvedPageIndex + 1} of {resolvedPageCount}
          </div>
          <Button
            variant="outline"
            onClick={() => updatePageIndex(Math.min(resolvedPageIndex + 1, resolvedPageCount - 1))}
            disabled={!canGoNext}
          >
            Next
          </Button>
        </div>
      </div>
    </div>
  )
}
