'use client'

import { useContext } from 'react'

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

import { Button } from '@repo/ui/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import { cn } from '@repo/ui/lib/utils'
import { TableContext } from './data-table'

export function DataTableViewOptions<TData>({
  className
}: {
  className: string
}) {
  const ctx = useContext(TableContext) as { table: Table<TData> } | null

  if (!ctx) {
    throw new Error('TableContext is null')
  }

  const { table } = ctx

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" className={cn('cursor-pointer', className)}>
          <Columns2Icon /> Colunas
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-44  *:cursor-pointer">
        {table
          .getAllColumns()
          .filter(
            (column) =>
              typeof column.accessorFn !== 'undefined' && column.getCanHide()
          )
          .map((column) => {
            return (
              <DropdownMenuCheckboxItem
                key={column.id}
                checked={column.getIsVisible()}
                onCheckedChange={(value) => column.toggleVisibility(!!value)}
              >
                {column.columnDef?.meta?.title ?? column.id}
              </DropdownMenuCheckboxItem>
            )
          })}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
