import { flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import { atom, useAtomValue, useSetAtom } from 'jotai'
import { useEffect, useMemo } from 'react'
import { StatsColumns } from '@/lib/columns'
import { ItemWithSelection } from '@/lib/table/defs'
import { InventoryColumns } from '@/lib/table/tanstack'
import {
  inventoryItemsCurrentPageAtom,
  mouseDragSelectionStateAtom,
  preferenceInventoryTab,
} from '@/state/atoms'

const columnVisibilityAtom = atom(get => {
  const itemTab = get(preferenceInventoryTab)
  if (!['2', '4'].includes(itemTab)) {
    return Object.fromEntries([...StatsColumns.map(x => [`stats.${x}`, false]), ['slots', false]])
  }
  return {}
})
export const InventoryTable = () => {
  const items = useAtomValue(inventoryItemsCurrentPageAtom)
  const setDragState = useSetAtom(mouseDragSelectionStateAtom)

  const columns = useMemo(() => {
    return [...Object.values(InventoryColumns)]
  }, [])

  const columnVisibility = useAtomValue(columnVisibilityAtom)

  const table = useReactTable<ItemWithSelection>({
    getRowId: row => row.item.unique_id.toString(),
    data: items,
    state: {
      columnVisibility,
    },
    columns,
    getCoreRowModel: getCoreRowModel(),
  })

  // Handle global mouse up to end drag selection
  useEffect(() => {
    const handleMouseUp = () => {
      setDragState(prev => ({ ...prev, isDragging: false }))
    }

    document.addEventListener('mouseup', handleMouseUp)
    return () => {
      document.removeEventListener('mouseup', handleMouseUp)
    }
  }, [setDragState])

  return (
    <div className="overflow-y-auto h-full mb-32">
      <table
        onContextMenu={e => {
          e.preventDefault()
          return
        }}
        className="border-spacing-x-2 border-separate"
      >
        <thead className="sticky top-0 z-10 select-none bg-white">
          {table.getHeaderGroups().map(headerGroup => (
            <tr className="" key={headerGroup.id}>
              {headerGroup.headers.map(header => (
                <th key={header.id} className="text-left">
                  {header.isPlaceholder
                    ? null
                    : flexRender(header.column.columnDef.header, header.getContext())}
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody className="divide-y divide-gray-200">
          {table.getRowModel().rows.map(row => (
            <tr key={row.id} className={''}>
              {row.getVisibleCells().map(cell => (
                <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
