import type { Table } from '@tanstack/react-table'

import { ActionIcon, Checkbox, Menu, Stack } from '@mantine/core'
import { IconColumns } from '@tabler/icons-react'

interface ColumnVisibilityMenuProps<T> {
  table: Table<T>
}

export function ColumnVisibilityMenu<T>({ table }: ColumnVisibilityMenuProps<T>) {
  const columns = table.getAllColumns().filter(col =>
    col.id !== '_selection' && col.getCanHide()
  )

  if (columns.length === 0) {
    return null
  }

  return (
    <Menu position="bottom-end" shadow="md" width={200}>
      <Menu.Target>
        <ActionIcon aria-label="Toggle columns" size="sm" variant="subtle">
          <IconColumns size={16} />
        </ActionIcon>
      </Menu.Target>

      <Menu.Dropdown>
        <Menu.Label>Toggle Columns</Menu.Label>
        <Stack gap="xs" p="xs">
          {columns.map(column => {
            const header = column.columnDef.header
            const label = typeof header === 'string' ? header : column.id

            return (
              <Checkbox
                checked={column.getIsVisible()}
                key={column.id}
                label={label}
                onChange={column.getToggleVisibilityHandler()}
                size="xs"
              />
            )
          })}
        </Stack>
      </Menu.Dropdown>
    </Menu>
  )
}
